如何从chrome扩展中打开的窗口中获取背景页面?

时间:2014-03-11 07:10:48

标签: javascript google-chrome google-chrome-extension google-chrome-app

该应用程序会从后台页面打开一个弹出窗口。打开的弹出窗口有js文件,可以访问后台页面的一些变量。但是当它试图访问时,

chrome.extension.getBackgroundPage()。variable_name它给出了“未定义”值

background.html包含

  chrome.browserAction.onClicked.addListener(function() {
return chrome.windows.create({
  url: "../popup.html",
  type: 'popup',
  height: 500,
  width: 200
}, function(window) {
  return console.log("opening a window");
});
});

的manifest.json

{
"name": "app name",
"version": "0.0.2",
"manifest_version": 2,
"minimum_chrome_version": "23",
"icons": {
    "16": "images/background-16.png",
    "48": "images/background-48.png",
    "128": "images/background-120.png"
},
 "background": {
  "page": "background.html"
},
"browser_action": {
  "default_icon": "images/background-16.png"

},
"default_locale": "en",
"permissions": [
  "storage",
"pushMessaging",
"notifications",
"tts",

]   }

1 个答案:

答案 0 :(得分:4)

如果使用getBackgroundPage(),则必须在回调函数中调用背景变量。

例如:

background.js

var cow = "mooh";
// The code to open myApp.html

myApp.js(与myApp.html相关联):

chrome.runtime.getBackgroundPage(function (backgroundPage) {
    console.log(backgroundPage.cow); // Displays "mooh".
});