mirror of
https://github.com/mdn/webextensions-examples.git
synced 2026-04-21 16:52:50 +02:00
3870a213bb
Check the value of "event.data" before dereferencing it, to avoid errors when void messages are sent using postMessage. And remove the "event.data.direction" truthness check, because the actual value is already tested at the next line.
29 lines
789 B
JavaScript
29 lines
789 B
JavaScript
/*
|
|
Listen for messages from the page.
|
|
If the message was from the page script, show an alert.
|
|
*/
|
|
window.addEventListener("message", function(event) {
|
|
if (event.source == window &&
|
|
event.data &&
|
|
event.data.direction == "from-page-script") {
|
|
alert("Content script received message: \"" + event.data.message + "\"");
|
|
}
|
|
});
|
|
|
|
/*
|
|
Send a message to the page script.
|
|
*/
|
|
function messagePageScript() {
|
|
window.postMessage({
|
|
direction: "from-content-script",
|
|
message: "Message from the content script"
|
|
}, "https://mdn.github.io");
|
|
}
|
|
|
|
/*
|
|
Add messagePageScript() as a listener to click events on
|
|
the "from-content-script" element.
|
|
*/
|
|
var fromContentScript = document.getElementById("from-content-script");
|
|
fromContentScript.addEventListener("click", messagePageScript);
|