Skip to content

Instantly share code, notes, and snippets.

@lmorchard
Created March 7, 2018 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmorchard/85fe22f3fb101e55cb5fcb53448a8a12 to your computer and use it in GitHub Desktop.
Save lmorchard/85fe22f3fb101e55cb5fcb53448a8a12 to your computer and use it in GitHub Desktop.
Messaging bridge in a webextension content script
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