Electron execute javascript as very first thing on a page

Viewed 2949

I have an electron app that opens a browser window with a certain web page. Now, I want to execute some javascript on that page as the very first thing. But whatever I try, it always seems to run after some other JS on the web page I open.

I tried some events like did-start-loading, e.g.:

window.webContents.on('did-start-loading', () => {
  window.webContents.executeJavaScript("console.log('test');");
})

And by putting it directly after the loadUrl:

window.loadURL(url);
window.webContents.executeJavaScript(`console.log('test');`);

But in both cases test gets logged after some other javascript has ran on the page.

1 Answers

Include a preload script when you are creating the browser window. Ex.

mainWindow = new BrowserWindow({
  webPreferences: {
    preload: path.join(__dirname, 'renderer.js')
  }
});

Here the renderer.js is loaded before any other js files of that window.

From the source code -

     /**
     * Specifies a script that will be loaded before other scripts run in the page.
     * This script will always have access to node APIs no matter whether node
     * integration is turned on or off. The value should be the absolute file path to
     * the script. When node integration is turned off, the preload script can
     * reintroduce Node global symbols back to the global scope. See example .
     */

Let me know if that works!

Related