【发布时间】:2013-06-26 21:35:13
【问题描述】:
更新
据我所知,不可能使用“sendMessage”函数将消息从后台脚本发送到内容脚本。但是有一个可怕的解决方法,
在内容脚本的 window.onload 中,向后台脚本发送消息:
chrome.runtime.sendMessage( { action: "messaging", window: "app" }, this.listenForFutureMessages );
同样在内容脚本中,具有以下功能:
listenForFutureMessages: function(someAction)
{
//Take some action based on the message
//If we want the background script to be able to contact
//us again, we need to give them another callback. This
//is because Chrome only allows one use per callback
chrome.runtime.sendMessage( { action: "messaging", window: "app" }, this.listenForFutureMessages );
},
在后台脚本中,有一个监听器来做这样的事情:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse)
{
if ( request.action === "messaging" )
{
//Save the callback for later
this.listeners[ request.window ] = sendResponse;
//Tell chrome we will be using the callback later
return true;
}
}
);
当您的后台脚本想要向内容脚本发送消息时,只需像这样调用它:
this.listeners[ "app" ]( { someProperty: "some value" } );
这是一种愚蠢的做法,但它实际上使这成为可能。希望这对需要此功能的其他人有所帮助。
原创
我无法从后台脚本向内容脚本发送消息。当我尝试查找选项卡 ID 时,它告诉我我没有权限,即使我的应用程序具有该权限。当我收到来自内容脚本的消息并打印出sender 对象时,它会显示tab.id = -1。向内容脚本发送消息的 API 需要标签 ID!
chrome.tabs.sendMessage(integer tabId,任意消息,函数 responseCallback)
错误:
chrome.tabs 不可用:您无权访问此 API。确保您的 manifest.json 中包含所需的权限或清单属性。
“未定义”的事件处理程序出错:无法调用未定义的方法“sendMessage”类型错误:无法调用未定义的方法“sendMessage” 在 chrome-extension://panoaieakcofaegcjfbmhndaekfgpijh/scripts/background.js:109:16 在 Event.dispatchToListener (event_bindings:356:21) 在 Event.dispatch_ (event_bindings:342:27) 在 Event.dispatch (event_bindings:362:17) 在 miscellaneous_bindings:167:33 在 Event.dispatchToListener (event_bindings:356:21) 在 Event.dispatch_ (event_bindings:342:27) 在 Event.dispatch (event_bindings:362:17) 在 Object.chromeHidden.Port.dispatchOnMessage (miscellaneous_bindings:253:22)
那么如何联系我的内容脚本? (我有多个窗口,需要能够单独联系他们)
我的清单:
{
"manifest_version": 2,
"name": "App",
"description": "App",
"version": "0.75",
"minimum_chrome_version": "27",
"offline_enabled": true,
"icons":
{
"16": "images/icon16.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
},
"app":
{
"background":
{
"scripts":
[
"scripts/background.js"
]
}
},
"permissions":
[
"unlimitedStorage",
"fullscreen",
{
"fileSystem":
[
"write"
]
},
"background",
"<all_urls>",
"tabs"
],
"update_url": "http://192.168.1.121/app.xml"
}
【问题讨论】:
-
不要把你的答案放在问题中。如果您有答案,请将其作为答案发布。
-
@kiamlaluno 我不认为这是一个答案。这是一种解决方法。
标签: google-chrome google-chrome-extension google-chrome-devtools google-chrome-app