Answer the question
In order to leave comments, you need to log in
How to do messaging in Chrome Extension?
I need to implement messaging in an extension. From content_script in background.js, I looked in the documentation for a way to exchange using window.postMessage() and window.addEventListener(), but no messages are sent. Through content_script, js code is loaded in my head.
Here is the code in background.js :
window.addEventListener("message", function(event) {
// We only accept messages from ourselves
if (event.source != window)
return;
if (event.data.type && (event.data.type == "FROM_PAGE")) {
console.log("Content script received: " + event.data.text);
port.postMessage(event.data.text);
}
}, false);
var s = document.createElement('script');
s.src = chrome.extension.getURL('inject.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
s.parentNode.removeChild(s);
};
window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
{
"name": "SaveImg",
"description": "Shows some of the features of the Context Menus API",
"version": "1.0",
"content_scripts": [{
"matches": ["http://*/*"],
"js": ["contentscript.js"]
}],
"permissions": ["contextMenus", "storage","activeTab"],
"background": {
"scripts": ["sample.js"]
},
"web_accessible_resources": ["inject.js"],
"manifest_version": 2
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question