问题
i try to post a message from a web_accessible_resource to a content-script of my chrome extension.
My Setup:
parts of my 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'}, '*');
Things i also tried that worked:
Adding a listener directly in run.js:
window.addEventListener("message", function(msg) {
if (msg.data.type === 'foo') {
// that one works
}
});
Posting a Message from a background script:
chrome.tabs.getCurrent(function (tab) {
chrome.tabs.sendMessage(tab.id, {type: "foo"});
});
Question:
What do i have to do? do i need to set some authorisation or something for my content-script or why does this not work???
回答1:
You can now enable the api to send messages directly from a webpage to your extension id
Enable in manifest
"externally_connectable": {
"matches": ["*://*.example.com/*"]
}
Send message from webpage:
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
function(response) {
if (!response.success)
handleError(url);
});
Receive in extension:
chrome.runtime.onMessageExternal.addListener(function(){});
See: https://developer.chrome.com/extensions/messaging#external-webpage
回答2:
just when i asked my question, i had an idea which of course...
... WORKED.
of course i need to attach a window.addEventListener in my content.js:
window.addEventListener("message", function(e) {
if (e.data.type === 'closeSidebar') {
// that works now
}
});
来源:https://stackoverflow.com/questions/18055800/window-postmessage-from-web-accessible-resource-to-content-script