mirror of
https://github.com/mdn/webextensions-examples.git
synced 2026-04-16 22:38:31 +02:00
2-way messaging
This commit is contained in:
14
README.md
14
README.md
@@ -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
|
||||
|
||||
18
page-to-extension-messaging/content-script.js
Normal file
18
page-to-extension-messaging/content-script.js
Normal 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"
|
||||
}, "*");
|
||||
}
|
||||
20
page-to-extension-messaging/manifest.json
Normal file
20
page-to-extension-messaging/manifest.json
Normal 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"]
|
||||
}
|
||||
]
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user