Skip to content

Commit

Permalink
Fix memory leak when listening to 'message' events from child iframes (
Browse files Browse the repository at this point in the history
  • Loading branch information
TheCloudlessSky authored Dec 6, 2022
1 parent 5b76ac8 commit fb2e2e8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/curvy-sheep-hope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@remote-ui/rpc': patch
---

Fix memory leak when listening to 'message' events from child iframes
24 changes: 17 additions & 7 deletions packages/rpc/src/adaptors/iframe-parent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,21 @@ export function fromIframe(
(event: MessageEvent) => void
>();

const iframeReadyPromise = new Promise<void>((resolve) => {
window.addEventListener('message', (event) => {
if (event.source !== target.contentWindow) return;
if (event.data === 'remote-ui::ready') {
resolve();
}
});

let resolveIFrameReadyPromise;

function onMessage(event) {
if (event.source !== target.contentWindow) return;

if (event.data === 'remote-ui::ready') {
window.removeEventListener('message', onMessage);
resolveIFrameReadyPromise();
}
}

const iframeReadyPromise = new Promise<void>(resolve => {
resolveIFrameReadyPromise = resolve;
window.addEventListener('message', onMessage);
});

return {
Expand All @@ -50,6 +58,8 @@ export function fromIframe(
self.removeEventListener(event, wrappedListener);
},
terminate() {
window.removeEventListener('message', onMessage);

if (shouldTerminate) target.remove();
},
};
Expand Down

0 comments on commit fb2e2e8

Please sign in to comment.