Skip to content

Instantly share code, notes, and snippets.

@domenic
Created November 15, 2018 22:18
Show Gist options
  • Save domenic/36cc626e1ed748d26afe6c83ca732ca0 to your computer and use it in GitHub Desktop.
Save domenic/36cc626e1ed748d26afe6c83ca732ca0 to your computer and use it in GitHub Desktop.
Portal activation data polyfill
const ACTIVATE_MESSAGE_PREFIX = "portal-activate-";
export function activateWithMessage(portal, messageType, messageData) {
portal.activate();
portal.postMessage({ type: ACTIVATE_MESSAGE_PREFIX + messageType, data: messageData });
}
export async function waitForActivateWithMessage() {
const [{ messageType, messageData }, event] = await Promise.all([
waitForActivateMessage(),
waitForActivateEvent()
])
return {
event,
messageType,
messageData
};
}
function waitForActivateMessage() {
return new Promise(resolve => {
window.addEventListener("message", e => {
if (typeof e.data === "object" &&
typeof e.data.type === "string" &&
e.data.type.startsWith(ACTIVATE_MESSAGE_PREFIX)) {
resolve({
messageType: e.data.type.substring(ACTIVATE_MESSAGE_PREFIX.length),
messageData: e.data.data
});
}
});
});
}
function waitForActivateEvent() {
return new Promise(resolve => {
window.addEventListener("portalactivate", resolve);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment