UPDATE在应用程序的sendMessage从后台脚本内容脚本失败
从我可以告诉,这是不可能从后台脚本发送消息到使用“的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" });
这是做这一个笨方法,但它使这实际上可能。希望这可以帮助任何需要此功能的人。
ORIGINAL 我无法从my background脚本发送消息到内容脚本。当我尝试查找标签ID时,它告诉我即使我的应用程序具有该权限,我也没有权限。当我收到来自内容脚本的消息并打印出sender
对象时,它会显示tab.id = -1
。将消息发送到内容脚本的API需要标签ID!
chrome.tabs.sendMessage(integer tabId, any message, function responseCallback)
错误:
chrome.tabs is not available: You do not have permission to access this API. Ensure that the required permission or manifest property is included in your manifest.json.
Error in event handler for 'undefined': Cannot call method 'sendMessage' of undefined TypeError: Cannot call method 'sendMessage' of undefined at chrome-extension://panoaieakcofaegcjfbmhndaekfgpijh/scripts/background.js:109:16 at Event.dispatchToListener (event_bindings:356:21) at Event.dispatch_ (event_bindings:342:27) at Event.dispatch (event_bindings:362:17) at miscellaneous_bindings:167:33 at Event.dispatchToListener (event_bindings:356:21) at Event.dispatch_ (event_bindings:342:27) at Event.dispatch (event_bindings:362:17) at 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
@kiamlaluno我不认为它是一个答案。这是一种解决方法。 –