1

我的 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'

非常感谢您的帮助,谢谢:)

4

1 回答 1

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);

因为default在javascript中被保留。(它与Switch 语句一起使用)
因此后台页面根本不会加载,检查它应该会导致类似这样的结果Uncaught SyntaxError: Unexpected token default at background.js:8

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

于 2012-12-07T18:03:06.477 回答