The preload attribute requires to use the file: protocol.
Because of the way electron and webpack work, it's a nightmare to use the preload attribute from the Renderer process, in the DOM.
The trick is to do it from the Main process.
In src/main/main.ts:
app.on('web-contents-created', (_event, contents) => {
contents.on('will-attach-webview', (_wawevent, webPreferences, _params) => {
webPreferences.preloadURL = `file://${__dirname}/webview-preload.js`;
});
});
In src/main/webview-preload.js:
document.addEventListener(
'DOMContentLoaded',
() => {
// YOUR CODE HERE
},
false
);
If this article helped you, please have a look at our Browser built with Electron, React, TypeScript and Redux: https://github.com/danielfebrero/bonb-browser
Top comments (0)