Skip to content

Commit

Permalink
fix: content-webapp messaging with postMessage for firefox (#33)
Browse files Browse the repository at this point in the history
- content-webapp events with abstract function
- use window.postMessage instead of custom event

See [here](https://stackoverflow.com/a/46081249/839513), and I can't
find the official documentation right now, but for security reasons,
Firefox desn't allow to pass an object inside a CustomEvent between
content-script and the host app.

You have to `cloneInto` it or something.
  • Loading branch information
baruchiro authored Mar 19, 2023
1 parent cebdb97 commit 8a45ff6
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
3 changes: 2 additions & 1 deletion src/content/content-events.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
addMessagingEventListener,
CONTENT_PORT_CONNECTION,
dispatchEvent,
READY_EVENT,
Expand Down Expand Up @@ -38,7 +39,7 @@ export const onScriptLoaded = (timeout = 5000, interval = 100) => {
};

export const listen = () => {
window.addEventListener(READY_EVENT, () => {
addMessagingEventListener(READY_EVENT, () => {
console.log('Ready event received from injected script');
isWebappReady = true;
});
Expand Down
6 changes: 3 additions & 3 deletions src/custom-elements/webapp-events.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { dispatchEvent, READY_EVENT, RESPONSE_PACKAGE_INFO_EVENT } from '../events-shared.js';
import { addMessagingEventListener, dispatchEvent, READY_EVENT, RESPONSE_PACKAGE_INFO_EVENT } from '../events-shared.js';
import * as store from './store.js';

export const initEventListenersAndStore = () => {
console.debug('Store initialized by referencing to the store', store);

window.addEventListener(RESPONSE_PACKAGE_INFO_EVENT, ({ detail }) => {
const { packageId, part, info } = detail;
addMessagingEventListener(RESPONSE_PACKAGE_INFO_EVENT, (data) => {
const { packageId, part, info } = data;
store.updatePackageInfo(packageId, part, info);
});

Expand Down
11 changes: 9 additions & 2 deletions src/events-shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ export const READY_EVENT = overlayPrefix + 'READY_EVENT';
export const CONTENT_PORT_CONNECTION = overlayPrefix + 'content-script';

export const dispatchEvent = (type, detail) => {
const event = new CustomEvent(type, { detail });
window.dispatchEvent(event);
window.postMessage({ type, detail });
};

export const addMessagingEventListener = (type, callback) => {
window.addEventListener('message', (event) => {
if (event?.data?.type === type) {
callback(event.data.detail);
}
});
};

0 comments on commit 8a45ff6

Please sign in to comment.