[英]Exchanging Settings from Options Page to Content-Script in Chrome Extension
I got a chrome extension which has the following manifest (part) 我得到了一个chrome扩展名,其中包含以下清单(部分)
"content_scripts": [
{
"matches": ["https://plus.google.com/*"],
"js": ["jquery-1.10.2.min.js","filter.js"]
}
],
"options_page": "settings.html",
I successfully read and write settings into the localstorage from within the "settings.js" which is called from the settings-page "settings.html" 我成功地从设置页面“ settings.html”中调用的“ settings.js”内部将设置读写到本地存储中
Now I need to access these values from the content-script "filter.js" 现在,我需要从内容脚本“ filter.js”访问这些值
I followed the example of http://developer.chrome.com/extensions/messaging.html creating a listener to the "settings.js" and a request to the "filter.js": 我按照http://developer.chrome.com/extensions/messaging.html的示例创建了对“ settings.js”的侦听器和对“ filter.js”的请求:
settings.js: settings.js:
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
filter.js: 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"});
});
It does not look like the listener and the request can "find each other". 它看起来不像侦听器,并且请求可以“互相查找”。
All I get on the console is: 我在控制台上得到的是:
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)
What am I doing wrong? 我究竟做错了什么?
Solved this by myself by adding an event page to the manifest: 我自己通过在清单中添加事件页面来解决此问题:
"background": {
"scripts": ["loader.js"],
"persistent": false
},
where I put the listeners and called those from the options script as well as from the content script. 我放置侦听器的位置,并从选项脚本和内容脚本调用了这些侦听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.