使用getBackgroundPage()给我:对象[对象窗口]没有方法'getFromStorage'

时间:2012-12-07 16:51:09

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

我在我的background.js中有这个:

var write = function (line) {
  if (localStorage["silent"] == true) {
    chrome.extension.getBackgroundPage().console.log(line);
  } else {
    alert(line);
  }
}
var getFromStorage = function (item, default) {
  if (localStorage[item] == undefined) {
    write("Could not find " + item + " in local storage...");
    return default;
  } else {
    return localStorage[item];
  }
}

var isOn = getFromStorage("isOn", true);
var silent = getFromStorage("silent", false);

这是我的popup.js:

var bgPage = chrome.extension.getBackgroundPage();
var isOn = bgPage.getFromStorage("isOn", true);
var silent = bgPage.getFromStorage("silent", false);

我收到了这个错误:

Object [object Window] has no method 'getFromStorage'

非常感谢帮助,谢谢:)

1 个答案:

答案 0 :(得分:2)

您应该更改后台脚本中的default参数

  var write = function (line) {
    if (localStorage["silent"] == true) {
      chrome.extension.getBackgroundPage().console.log(line);
    } else {
      alert(line);
    }
  }
  var getFromStorage = function (item, d) {
    if (localStorage[item] == undefined) {
      write("Could not find " + item + " in local storage...");
      return d;
    } else {
      return localStorage[item];
    }
  }

  var isOn = getFromStorage("isOn", true);
  var silent = getFromStorage("silent", false);

因为javascript中保留了default。 (它与Switch statement)一起使用 因此,后台页面根本不会加载,检查它应该会产生类似Uncaught SyntaxError: Unexpected token default at background.js:8

的内容

然后导致错误Object [object Window] has no method 'getFromStorage' 在你的弹出脚本中,因为getFromStorage实际上从未在后台脚本中加载,因为在第8行终止