DEV Community

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

Posted on

4 4 1 1 1

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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay