我已经为此苦苦挣扎了好几天,我扩展程序的内容脚本似乎缺少权限或某些东西,我在API文档中进行了搜索,却一无所获。
如果我使用以下代码从内容页面发送消息,而不是向内容页面发送消息,则消息传递有效:
从后台页面:
var messageCallback = function (e) {
var nodeMessage = JSON.parse(e.data);
switch (nodeMessage.ExecutionType) {
case 0:
chrome.tabs.create({ url: nodeMessage.Url }, function (tab) {
//injects injected.js NOT messages.js
injectCode(tab.id);
chrome.tabs.sendMessage(tab.id,nodeMessage);
});
break;
//some other switch cases...
从内容脚本中:
chrome.runtime.onMessage.addListener(function (message) {
console.log('Message received');
var event = new CustomEvent("foo_receive", {
detail: message,
bubbles: true
});
console.log('Event sent');
document.dispatchEvent(event);
});
我的清单如下所示:
{
"manifest_version": 2,
"name": "extesnion_name",
"short_name": "thing",
"description": "long sentence",
"version": "1.0.0",
"icons": { "16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png" },
"permissions": ["background", "tabs", "<all_urls>" ],
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts":[
{
"matches": ["<all_urls>"],
"js": ["messages.js"],
}
],
"web_accessible_resources": ["injected.js"]
}
chrome控制台中显示以下内容:
内容脚本:
和背景页面:
如果chrome.runtime.onMessage
未定义,则在运行内容脚本时,您会在控制台中看到一条错误消息,告诉您。
实际情况是,您chrome.runtime
在控制台中看到的是受限版本,因为您正在访问网页上下文而不是内容脚本上下文。请参阅此答案以从控制台访问内容脚本上下文。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句