Skip to content

Instantly share code, notes, and snippets.

@theArina
Last active January 14, 2022 07:35
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 theArina/20ba29aaadc928c9a0fb37e1472a6bb1 to your computer and use it in GitHub Desktop.
Save theArina/20ba29aaadc928c9a0fb37e1472a6bb1 to your computer and use it in GitHub Desktop.
electron-iframe-preload-bug-example
<!DOCTYPE html>
<html>
<body>
<webview
style="height:97vh"
src="https://www.eventbrite.com/e/built-to-spill-tickets-96116339559"
preload="./preload.js"
nodeintegrationinsubframes="true"
webpreferences="contextIsolation=no"
/>
</body>
</html>
<script>
const webview = document.querySelector('webview');
const onDomReady = () => {
webview.openDevTools();
webview.removeEventListener('dom-ready', onDomReady);
/*
If you comment "webview.addEventListener('ipc-message', ...);"
and leave "webview.send('test-back');" in "dom-ready" event
it also will work fine (necessary preload will be loading)
*/
webview.addEventListener('ipc-message', (event) => {
console.log(event.channel);
webview.send('test-back');
})
}
webview.addEventListener('dom-ready', onDomReady);
</script>
const { app, BrowserWindow } = require('electron');
process.traceProcessWarnings = true;
app.commandLine.appendSwitch('disable-site-isolation-trials');
app.on('ready', () => {
let mainWindow = new BrowserWindow({
show: true,
webPreferences: {
contextIsolation: false,
webviewTag: true,
nodeIntegration: true,
nodeIntegrationInSubFrames: true,
plugins: true,
javascript: true,
}
});
mainWindow.loadFile(`${__dirname}/index.html`);
mainWindow.on('closed', () => mainWindow = null);
});
{
"name": "iframe-preload-example",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"dependencies": {
"electron": "16.0.0"
}
}
const { ipcRenderer } = require('electron');
console.log('location.href:', location.href);
const IFRAME_MESSAGE = 'test-iframes';
window.addEventListener('message', (event) => {
if (event.data.channel !== IFRAME_MESSAGE) return;
sendPostMessageToAllIframes();
});
if (process.isMainFrame) {
ipcRenderer.on('test-back', (event) => {
console.log('on-test-back');
// Comment line below and see that necessary preload is loading fine
sendPostMessageToAllIframes();
});
}
/*
Although if we write the following:
"window.addEventListener('DOMContentLoaded', () => {
sendPostMessageToAllIframes();
});"
instead of ipc messages, it will work fine (necessary preload also will be loading)
*/
window.addEventListener('DOMContentLoaded', () => {
ipcRenderer.sendToHost('test-to');
});
function sendPostMessageToAllIframes() {
const iframes = document.querySelectorAll('iframe');
iframes.forEach((iframe) => {
iframe.contentWindow.postMessage({ channel: IFRAME_MESSAGE, }, '*');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment