How to pass variable value between background scripts in chrome extensions

I am developing a Google Chrome extension. I have the value set for a variable in one of my background javascript files (example.js). I need to get or pass this value to another javascript backgound file (extjs.js). How should I do it? Is there a concept for a global variable? I do not get any errors in the 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 something is missing.

Regards, Nihil

+2
source share
1 answer

All background scripts use the same JS context, so any variable / function declared in one of the scripts is accessible to everyone else (the loading order plays a role).

Chrome HTML- <script> . . :

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

, chrome://extensions Developer mode. " ", , DevTools .


UPDATE:

, - ( trial()) ( ).

var result trial(), . (, example.js.)

:

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
+2

All Articles