Created
March 7, 2018 19:38
-
-
Save lmorchard/85fe22f3fb101e55cb5fcb53448a8a12 to your computer and use it in GitHub Desktop.
Messaging bridge in a webextension content script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { CHANNEL_NAME } from "../lib/constants"; | |
// Relay backend port messages to content | |
let port; | |
function connect() { | |
port = browser.runtime.connect({ name: CHANNEL_NAME }); | |
port.onDisconnect.addListener(() => { | |
port = null; | |
reconnect(); | |
}); | |
port.onMessage.addListener(message => { | |
window.postMessage({ ...message, channel: `${CHANNEL_NAME}-web` }, "*"); | |
}); | |
} | |
// Relay content messages to backend port if the channel name matches | |
// (Not a security feature so much as a noise filter) | |
window.addEventListener("message", event => { | |
if ( | |
port && | |
event.source === window && | |
event.data && | |
event.data.channel === `${CHANNEL_NAME}-extension` | |
) { | |
port.postMessage({ ...event.data, location: window.location.href }); | |
} | |
}); | |
connect(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment