Create a global crystal variable application

I am creating a Chrome application. this is my manifest file.

{
//...... description and other things
//.......
"app": {
    "background": {
        "scripts": ["js/main.js"]
    }
},
// other things

}

and in my js / main.js file I defined a global variable as globalData.

    chrome.app.runtime.onLaunched.addListener(function() {

  chrome.app.window.create('/dashboard.html', {
    'bounds': {
      'width': screen.availWidth,
      'height': screen.availHeight
    }
  });
});
var globalData;

(for this I need a variable available for all execution). In dashboar.html, I included the services.js files. Is there a way I can use this globalData variable in services.js.

+4
source share
1 answer

In any window of the Chrome application, you can access the backgroundPage and therefore also access the variables assigned to its global object (top level var, how you are automatically connected)

Try the following:

chrome.runtime.getBackgroundPage(function(bgpage) {
  console.log(bgpage.globalData);
})

( javascript-):

// in bgpage
var globalData = {};
globalData.apples = ['red', 'green'];

// in app window
var globalData;
chrome.runtime.getBackgroundPage(function(bgpage) {
   globalData = bgpage.globalData;
   main();
})
function main() {
   console.log(globalData.apples);
}
+5

Source: https://habr.com/ru/post/1530366/


All Articles