我尝试将消息从 web_accessible_resource 发布到我的 Chrome 扩展程序的内容脚本。
我的设置:
manifest.json 的部分内容:
"content_scripts": [{
"matches": ["http://*/*"],
"js": ["content.js"]
}],
"web_accessible_resources": ["run.js"]
content.js
// this listener is never triggered ;-(
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type === 'foo') {
// do whatever i want if request.type is foo
}
});
run.js
window.postMessage({type: 'foo'}, '*');
我也尝试过有效的方法:
直接在run.js中添加监听器:
window.addEventListener("message", function(msg) {
if (msg.data.type === 'foo') {
// that one works
}
});
从后台脚本发布消息:
chrome.tabs.getCurrent(function (tab) {
chrome.tabs.sendMessage(tab.id, {type: "foo"});
});
问题:
我必须做什么?我是否需要为我的内容脚本设置一些授权或其他内容,或者为什么这不起作用???
最佳答案
您现在可以启用 API 将消息直接从网页发送到您的扩展程序 ID
在 list 中启用
"externally_connectable": {
"matches": ["*://*.example.com/*"]
}
从网页发送消息:
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
function(response) {
if (!response.success)
handleError(url);
});
在扩展中接收:
chrome.runtime.onMessageExternal.addListener(function(){});
参见:https://developer.chrome.com/extensions/messaging#external-webpage
关于javascript - window.postMessage 从 web_accessible_resource 到内容脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18055800/