I am wanting to send messages from javascript injected into a webview element using webview.executeJavaScript
, to main or renderer scripts. What I could find on the web sounds pretty straightforward: Add const { ipcRenderer } = require('electron');
to the webview preload script, then call ipcRenderer.send()
or ipcRenderer.sendToHost()
from the webview javascript content. However, in all my attempts, I get errors saying ipcRenderer
is not defined in the injected javascript. Maybe this works if the ipcRenderer
call is in the page loaded into the webview (but not for injected js), but I cannot test that as I have no control over the content.
One thing I looked at talked about using webContents
instead:
https://www.electronjs.org/docs/latest/api/web-contents#contentssendchannel-args
but that didn’t work either.
Another said that objects attached to window
in the preload script would be accessible in the webview content script, but that didn’t work either.
Communication to site inside <webview>
byu/akujinhikari inelectronjs
Here is my code:
index.html:
<webview id="test_webview" preload="webview_preload.js" src="https://192.168.1.182/"></webview>
OR
<webview id="test_webview" preload="webview_preload.js" src="https://192.168.1.182/" disablewebsecurity></webview>
renderer.js:
function init() {
let wv = document.getElementById("test_webview");
wv.addEventListener('dom-ready', () => {
wv.executeJavaScript('alert("webview_preload.js injected"); try { ipcRenderer.send("ping"); } catch(e) { alert(e); }; try { webContents.send("ping"); } catch(e) { alert(e); }; try { window.sendData("ping"); } catch(e) { alert(e); }');
});
}
window.addEventListener("DOMContentLoaded", init);
webview_preload.js:
const { ipcRenderer, webContents } = require('electron');
window.sendData = (data) => {
ipcRenderer.send("toMain", ["HELLO from webview preload"])
}
The alert("webview_preload.js injected")
injected from renderer.js verifies the js is being injected; the following 3 try/catches show me all my attempts fail, showing that neither ipcRenderer
, webContents
, nor window.sendData
is defined.