Load JavaScript in an Electron BrowserWindow

Share this video with your friends

Send Tweet

In this lesson we’ll load javascript into the BrowserWindow and display the Electron version on the page. Loading javascript into Electron is almost exactly the same as loading it into the browser, however it is a best practice to use the require syntax.

Frederic Rey
Frederic Rey
~ 7 years ago

Hello! I just started the course and it looks like the 2nd ('Load CSS ...') and 3rd(current one) videos have been switched, just wanted to let you know ;)

Clearcode Py04
Clearcode Py04
~ 7 years ago

@Frederic Rey: I totally agree - it's a little confusing. I Guess Cameron could just simply change the order of episodes 2-3.

Matias
Matias
~ 7 years ago

There's another way to contact Cameron?

Will Vincent
Will Vincent
~ 5 years ago

Update for anyone watching now, and using Electron 5 or greater. Node integration is no longer enabled by default, you must explicitly enable it before require will work now...

Instead of mainWindow = new BrowserWindow() you'll now want:

mainWindow = new BrowserWindow({
    webPreferences: {
        nodeIntegration: true
    }
});
Dmitriy Lutsenko
Dmitriy Lutsenko
~ 5 years ago

It should be 2nd lesson.

Will Kelly
Will Kelly
~ 5 years ago

Had an error with require, turns out electron > 5.0.0 doesn't by default allow node integration for any renderer.

https://electronjs.org/docs/tutorial/security#2-do-not-enable-nodejs-integration-for-remote-content

Branislav Remen
Branislav Remen
~ 3 years ago

Nov 2021 - Electron 15.3.0, following code will work:

  1. remove script from index.html
  2. index.js:
mainWindow = new BrowserWindow({
        webPreferences: {
            preload: path.join(__dirname, 'renderer.js')
        }
    });
    mainWindow.loadFile('index.html');
  1. renderer.js:
window.addEventListener('DOMContentLoaded', () => {
    const versionEl = document.querySelector('#version');
    versionEl.innerText = process.versions.electron;
    console.log(process.versions);
});