Home

Solved window.require is not a function in Electron app

I got this error when I recently tried to upgrade my Calculator which is developed in electron few years ago.

Later I figured out that the Electron developers had changed the default values of nodeIntegration and webviewTag.

The solution is to enable it when you create a new BrowserWindow.

mainWindow = new BrowserWindow({
  width: 960,
  height: 720,
  webPreferences: {
    nodeIntegration: true,
  },
});

You can use preload.js which will be loaded before other scripts run in the page.

This script will always have access to both electron APIs and node APIs(and also the browser APIs) no matter whether node integration is turned on or off. Using preload.js, you can expose any functionality or APIs by setting an global on window

const path = require('path');

mainWindow = new BrowserWindow({
  width: 300,
  height: 455,
  webPreferences: {
    preload: path.join(__dirname, 'preload.js'),
  },
});

Here are few examples:

const _setImmediate = setImmediate;
const _clearImmediate = clearImmediate;
process.once('loaded', () => {
  global.setImmediate = _setImmediate;
  global.clearImmediate = _clearImmediate;
});

For more examples read this post: How to use preload script in electron



Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments