2-way messaging

This commit is contained in:
Will Bamberg
2015-09-17 22:12:53 -07:00
parent f8c1ef9f82
commit 29697b03f8
3 changed files with 52 additions and 0 deletions

View File

@@ -68,3 +68,17 @@ All it does is: when the user clicks the button, open "my-page.html" in a new ta
* how to listen for browser action clicks in a background script
* how to open a page packaged with your extension
## page-to-extension-messaging ##
This extension includes:
* a content script, which is injected only into: "https://mdn.github.io/webextensions-examples/content-script-page-script-messaging.html"
The content script listens for messages from the same window posted using window.postMessage. When the content script receives such a message, it displays an alert.
To test it out, visit https://mdn.github.io/webextensions-examples/content-script-page-script-messaging.html and press the button.
### What it shows ###
* how to send a message from a page script to a content script

View File

@@ -0,0 +1,18 @@
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 + "\"");
}
});
var fromContentScript = document.getElementById("from-content-script");
fromContentScript.addEventListener("click", messagePageScript);
function messagePageScript() {
window.postMessage({
direction: "from-content-script",
message: "Message from the content script"
}, "*");
}

View File

@@ -0,0 +1,20 @@
{
"manifest_version": 2,
"name": "Page to extension messaging",
"version": "1.0",
"applications": {
"gecko": {
"id": "page-to-extension-messaging@mozilla.org"
}
},
"content_scripts": [
{
"matches": ["https://mdn.github.io/webextensions-examples/content-script-page-script-messaging.html"],
"js": ["content-script.js"]
}
]
}