Skip to content

Instantly share code, notes, and snippets.

@Macil
Last active February 15, 2023 05:14
Show Gist options
  • Save Macil/9f8b3c9f4e671d4e422bd34901ff882f to your computer and use it in GitHub Desktop.
Save Macil/9f8b3c9f4e671d4e422bd34901ff882f to your computer and use it in GitHub Desktop.
// This code is assumed to be part of one of the extension's content scripts
function addIframe() {
const iframe = document.createElement('iframe');
iframe.addEventListener('load', () => {
iframe.contentWindow.postMessage({
eventName: 'init',
iframeSrc: 'https://xkcd.com/' // whatever url you want. Probably will be a URL to your own domain in practice
}, '*');
}, false);
iframe.src = chrome.runtime.getURL('iframe.html');
function messageHandler(event) {
if (event.source !== iframe) return;
console.log('got message from iframe', event.data);
}
// If you remove the iframe from the page later, make sure you remove this listener too! Otherwise if this function is
// called many times over a session, you'll have a memory leak of more and more listeners being added to the page.
window.addEventListener('message', messageHandler);
document.body.appendChild(iframe);
}
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script src="iframe.js"></script>
</head>
<body>
</body>
</html>
'use strict';
// This file and iframe.html must be listed in the extension's manifest.json under the web_accessible_resources section
let parentOrigin;
let iframe;
window.addEventListener('message', function(event){
if (iframe && event.source === iframe.contentWindow) {
const message = {innerFrameData: event.data};
const transferableList = event.data && event.data.transferableList;
window.parent.postMessage(message, parentOrigin, transferableList);
} else if (event.origin.match(/^https:\/\/\w+\.google\.com$/)) { // needs to match url of the site your extension puts the iframe in
if(event.data.eventName === 'init'){
parentOrigin = event.origin;
setupIFrame(event.data.iframeSrc);
} else {
iframe.contentWindow.postMessage({parentOrigin, parentData: event.data}, '*', event.data.transferableList);
}
} else {
throw new Error('Message from unknown source');
}
});
function setupIFrame(src){
iframe = document.createElement('iframe');
iframe.src = src;
iframe.setAttribute('style', 'height: 100%; width: 100%; border: 0; margin: 0;');
iframe.addEventListener('load', () => {
window.parent.postMessage({eventName: 'innerFrameLoaded'}, parentOrigin);
}, false);
document.body.appendChild(iframe);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment