I'm trying to communicate from a web page to an extension and vice versa.
To do so, I looked at the Mozilla documentation here : https://developer.mozilla.org/fr/Add-ons/WebExtensions/Content_scripts#Communicating_with_the_web_page
And it has a simple example, but I can't make it work. On the web page script, I have this :
// page-script.js
var messenger = document.getElementById("from-page-script");
messenger.addEventListener("click", messageContentScript);
function messageContentScript() {
window.postMessage({
direction: "from-page-script",
message: "Message from the page"
}, "*");
On the content scripts page in the extension :
// content-script.js
window.addEventListener("message", function(event) {
if (event.source == window &&
event.data.direction &&
event.data.direction == "from-page-script") {
alert("Content script received message: \"" + event.data.message + "\"");
}
});
I installed the extension (as a temporary one, I uploaded my xpi file), then I used the "Debugging" method of API WebExtensions, and put a breakpoint into the listener, but whenever I call the PostMessage, the extension never seems to receive the event, the breakpoint is never triggered.
Is it possible to communicate this way between a web page and an extension ? Or is there another one ?
The problem was in the manifest of my extension. I declared my content script as a background script.
So, instead of writing this :
"background": {
"scripts": ["myscript.js"],
"persistent": true
},
You have to declare the script like this :
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["myscript.js"]
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With