我一直在搜索SO并阅读谷歌文档,但我似乎无法找到解决方案。
我的Chrome扩展程序正在注入内容脚本,我想设置onRequest.listener
以便将sendRequests发送到内容脚本。这是the script我曾经用于onRequest.listener
。问题是我出于某种未知原因不断收到此错误。
错误讯息:
Uncaught TypeError: Cannot ready property 'onRequest' of undefined
contentscript.js line 1;
以下是相关代码......
的manifest.json
{
"name": "Injector Extension",
"version": "1.0",
"manifest_version": 1,
"icons": { "128": "icon.png" },
"browser_action": {
"default_icon": "icon.png",
"default_title": "Injector Extension",
"default_popup": "popup.html"
},
"options_page": "options.html",
"background": {
"page": "background.html"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*",
"unlimitedStorage"],
"content_scripts": [{
"matches": [" (injector specific url) "],
"js": ["contentscript.js"]
}],
"web_accessible_resources": ["js/script.js"]
}
内容脚本
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "fromPopup") {
// Send JSON data back to Popup.
sendResponse({data: "from Content Script to Popup"});
} else {
sendResponse({}); // snub them.
}
});
弹出
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "fromPopup", tabid: tab.id}, function(response) {
console.log(response.data);
});
});
答案 0 :(得分:5)
chrome.extension.onRequest.addListener
仅适用于扩展上下文。它不会在内容脚本中运行。
chrome.extension.sendRequest
适用于内容脚本上下文
相应更新并将有效。
编辑:举例说明简单的消息传递:
扩展程序脚本:
chrome.extension.onRequest.addListener(function(r,s,sr){
if(r==='HELLO') return sr.call(this,'BACK AT YOU');
});
内容脚本:
chrome.extension.sendRequest('HELLO', function(data){ alert(data); });
// will alert "BACK AT YOU"