Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enableRemoteModule is missing from Electron v14 TypeScript type definitions

I've upgraded to Electron 14, refactored my project to accomodate for the "Removed: remote module" breaking change, but I'm unable to compile it due to the following TypeScript error:

Type '{ plugins: true; nodeIntegration: true; contextIsolation: false; enableRemoteModule: true; backgroundThrottling: false; webSecurity: false; }' is not assignable to type 'WebPreferences'.

Object literal may only specify known properties, and 'enableRemoteModule' does not exist in type 'WebPreferences'.ts(2322)

electron.d.ts(12612, 5): The expected type comes from property 'webPreferences' which is declared here on type 'BrowserWindowConstructorOptions'

The affected code:

const window = new electron.BrowserWindow({
    // ...
    webPreferences: { 
      plugins: true, 
      nodeIntegration: true, 
      contextIsolation: false,
      enableRemoteModule: true, 
      backgroundThrottling: false,
      webSecurity: false 
    }, 
    // ...
  });

Is this a bug or an intentional change in Electron v14? What's a workaround?

like image 361
noseratio Avatar asked Dec 23 '22 15:12

noseratio


1 Answers

Now Electron 14.0.1 is out, and this is how I could enable remote modules for both Main and Renderer processes (your webPreferences settings may vary).

First, install @electron/remote package (important: no --save-dev, as it needs to be bundled):

npm install "@electron/remote"@latest

Then, for Main process:

  // from Main process
  import * as electron from 'electron';
  import * as remoteMain from '@electron/remote/main';
  remoteMain.initialize();
  // ...

  const window = new electron.BrowserWindow({
    webPreferences: { 
      plugins: true, 
      nodeIntegration: true, 
      contextIsolation: false,
      backgroundThrottling: false,
      nativeWindowOpen: false,
      webSecurity: false 
    } 
    // ...
  });

  remoteMain.enable(window.webContents);

For Renderer process:

  // from Renderer process
  import * as remote from '@electron/remote';

  const window = new remote.BrowserWindow({
    webPreferences: { 
      plugins: true, 
      nodeIntegration: true, 
      contextIsolation: false,
      backgroundThrottling: false,
      nativeWindowOpen: false,
      webSecurity: false 
    } 
    // ...
  });

  // ...
  // note we call `require` on `remote` here
  const remoteMain = remote.require("@electron/remote/main");
  remoteMain.enable(window.webContents);

Or, as one-liner:

require("@electron/remote").require("@electron/remote/main").enable(window.webContents);

It's important to note, if created from a Renderer process like that, BrowserWindow is a remote object, i.e. a Renderer proxy to a BrowserWindow object created inside the Main process.

like image 106
noseratio Avatar answered Dec 28 '22 11:12

noseratio