Google Bot Google Bot - 5 months ago 8
jQuery Question

How to access a object residing in another javascript file through javascript file in chrome extenstion?

Here I have 2 JavaScript files and I modified the

manifest.json
as below to avoid errors:

{
"matches": [
"*://example.com"
],
"all_frames": true,
"css":[
"css/d.css",
"css/bootstrap.min.css"
],
"js": [
"scripts/jquery.min.js",
"scripts/home/msg.js",
"scripts/home/modify.js"
]
}


Now I have an object residing in the
msg.js
file and I'm only including relevant parts:

o = {
"timeStamps" : t.slice(),
"messages" : Object.assign({}, a)
}
console.log(o);
help(o.messages, o.timeStamps.length);

function help_final(){
return o;
}


Here
console.log(o)
is working fine. So i want this object
o
in another file named
modified.js
.

Here is my
modified.js
file:

message_object = help_final();
$.getScript( "msg.js" )
.done(function( script, textStatus ) {
console.log( textStatus );
//here i need to access the object o and store it as global variable
})
.fail(function( jqxhr, settings, exception ) {

});

$(document).ready(function() {
console.log("ready!");
//I need to access the obj here

console.log(message_object);
});

Answer

You should export the function so you can access the object outside of that specific file to the browser so that all your files can access the object (from what it looks like your trying to store it globally anyway).

So in msg.js just do at the bottom (assuming this is only to be used in a browser) window.message_object = help_final;

And then just modify your code a bit in the other files to call message_object() to get the o object.

You should also look into using javascript prototypes https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype