nikhil
nikhil

Reputation: 111

How to pass a variable value between background scripts in chrome extensions

I am developing a google chrome extension. I have a value set for a variable in one of my background javascript files(example.js). I need to access or pass this value to another backgound javascript file(extjs.js). How do I do it? Is there a global variable concept? I am not getting any error in my browser console.

my manifest.json

{
"name": "Example",
"version": "31.0.1650.57",
"manifest_version": 2,
"background":{
"scripts":["common.js","example.js","extjs.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["myscript.js"]
}
]
}

my example.js

function trial()
{
/... some functionality../
var result = data;
}

my extjs.js

alert(result);

I know I am missing something.

Regards, Nikhil

Upvotes: 2

Views: 3008

Answers (1)

gkalpak
gkalpak

Reputation: 48211

All background scripts share the same JS context, so any variable/function declared in one of the scripts is available to all the others (the order of loading plays a role of course).

When specifying one or more background scripts, Chrome automatically creates a minimal HTML page and inserts some <script> tags in the body. E.g. your automatically generated background page should look something like this:

<html>
    <head></head>
    <body>
        <script src="common.js"></script>
        <script src="example.js"></script>
        <script src="extjs.js"></script>
    </body>
</html>

You can take a look at your background page by navigating to chrome://extensions and checking the Developer mode checkbox. Then, under each extension there is link labelled "background page", which you can click to open a DevTools console of your background page.


UPDATE:

I just notice you are trying to access a function-local variable (defined in trial() function) from the global context (which is not possible).

Since var result is defined inside the trial() function, it is not accessible outside the scope of the function. (I.e. you won't be able to reference it from example.js either.)

You need to change your code like this:

example.js:

var outer_result = 0;
function trial() {
    var inner_result = 1;   // <-- this is a local variable
    outer_result = 2;       // <-- this is a global variable
}
// `inner_result` is undefined outside the function

extjs.js:

console.log(outer_result);   // <-- '0' since `trial()` is not invoked yet
console.log(inner_result);   // <-- 'undefined' since it is never defined

trial();   // <-- executing `trial()` function

console.log(inner_result);   // <-- 'undefined' since it is function-local
console.log(outer_result);   // <-- '2' since `trial()` modified it

Upvotes: 2

Related Questions