|
// Content scripts could listen for events coming either from |
|
// page scripts or add-on host, by setting event listener on |
|
// a window. |
|
|
|
window.addEventListener("message", function onMessage(event) { |
|
if (event.origin === "add-on:A") { |
|
// Message from addon:A |
|
} else if (event.origin === document.URL) { |
|
// Message from page script |
|
} else if (event.origin === self.origin) { |
|
// Message from content-script itself. |
|
} else { |
|
// Unknown message, possibly from malicius evil.com |
|
} |
|
}); |
|
|
|
// 1. Content script can send messages to itself. |
|
// |
|
// Note that event handlers set by page scripts won't be invoked, since |
|
// `self.origin !== document.URL`, only target able to receive this message |
|
// will be a content script itself. |
|
window.postMessage("hello", self.origin); |
|
|
|
// 2. Content script can send messages to an add-on host. |
|
// |
|
// Content script also could post messages to the add-on host, but again |
|
// page scripts won't be invoked, since `"add-on:A" !== documentURL`. Also |
|
// Also above `onMessage` handler wan't be invoked either since |
|
// `"add-on:host" !== self.origin`. |
|
window.postMessage("hello add-on", "add-on:A"); |
|
|
|
// 3. Content script can send messages to pages scripts |
|
// |
|
// This will invoke handler registered by a page script |
|
// since because host is `document.URL`. Note that add-on |
|
// host and content scripts won't recieve this message |
|
// since they have diff targetOrigin. |
|
window.postMessage("hello page", document.URL); |