Javascript 在Chrome扩展中将设置从选项页交换到内容脚本

Javascript 在Chrome扩展中将设置从选项页交换到内容脚本,javascript,jquery,google-chrome-extension,Javascript,Jquery,Google Chrome Extension,我得到了一个chrome扩展,它有以下清单(部分) 我成功地从“settings.js”中读取设置并将其写入localstorage,该设置从设置页面“settings.html”调用 现在我需要从内容脚本“filter.js”中访问这些值 我以创建“settings.js”的侦听器和“filter.js”的请求为例: settings.js: chrome.runtime.sendMessage({greeting: "hello"}, function(response) {

我得到了一个chrome扩展,它有以下清单(部分)

我成功地从“settings.js”中读取设置并将其写入localstorage,该设置从设置页面“settings.html”调用

现在我需要从内容脚本“filter.js”中访问这些值

我以创建“settings.js”的侦听器和“filter.js”的请求为例:

settings.js:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
        console.log(response.farewell);
    });
filter.js:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });
它看起来不像侦听器和请求可以“找到对方”

我在控制台上看到的是:

Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined
        at chrome-extension://opojapnnibghjncfphindgjhddljcgej/settings.js:30:23
        at extensions::messaging:320:11
        at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
        at Event.dispatchToListener (extensions::event_bindings:386:22)
        at Event.dispatch_ (extensions::event_bindings:371:27)
        at Event.dispatch (extensions::event_bindings:392:17)
        at dispatchOnDisconnect (extensions::messaging:280:27)

我做错了什么

通过在清单中添加事件页,我自己解决了这个问题:

"background": {
    "scripts": ["loader.js"],
    "persistent": false
  },

在这里,我放置了侦听器,并从选项脚本和内容脚本调用了这些侦听器。

如果您使用
chrome.storage
API而不是
localstorage
来保存设置,可能会更简单。您可以直接从内容脚本访问
chrome.storage
,因此不需要在后台发送消息。您应该早就知道了……)
"background": {
    "scripts": ["loader.js"],
    "persistent": false
  },