DEV Community

Cover image for How to use preload script in Electron Webview with React
dani
dani

Posted on

How to use preload script in Electron Webview with React

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`;
  });
});
Enter fullscreen mode Exit fullscreen mode

In src/main/webview-preload.js:

document.addEventListener(
  'DOMContentLoaded',
  () => {
    // YOUR CODE HERE
  },
  false
);
Enter fullscreen mode Exit fullscreen mode

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)