简体   繁体   English

创建一个全局变量chrome app

[英]create a global variable chrome app

I am creating a Chrome app. 我正在创建一个Chrome应用。 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 have defined a global variable as globalData. 在我的js / main.js文件中,我将全局变量定义为globalData。

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

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

(purpose of doing that I need a variable that available whole runtime). (这样做的目的我需要一个可用的整个运行时的变量)。 In dashboar.html I have included services.js files. 在dashboar.html中,我包含了services.js文件。 Is there a way that I can use that globalData variable in services.js. 有没有办法可以在services.js中使用该globalData变量。

From any chrome app window you can access the backgroundPage, and thus also access variables assigned to its global object (top level var like you have are automatically attached) 在任何Chrome应用程序窗口中,您都可以访问backgroundPage,从而也可以访问分配给其全局对象的变量(与您自己连接的顶级var

Try this: 试试这个:

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

You can also save a reference to the background page, or save a reference to the global data object itself (usual javascript caveats apply): 您还可以保存对背景页面的引用,或保存对全局数据对象本身的引用(通常的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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM