brrd / electron-tabs

Tab component for Electron
MIT License
697 stars 130 forks source link

Try to enable @electron/remote inside an electron-tab #153

Closed ruben-cruz closed 2 years ago

ruben-cruz commented 2 years ago

Hi, I've tried to enable @electron/remote inside an electron-tab webview, but without success. Does anyone know if it's possible and how can we do that?

My dependencies versions are:

"electron": "^19.0.2",
"@electron/remote": "^2.0.8",
"electron-tabs": "^0.7.3",
ruben-cruz commented 2 years ago

Anyone can help or give some advice?

ruben-cruz commented 2 years ago

For anyone getting this problem, the way to fix is:

  1. Enable the webContents for each webview on 'will-attach-webview' event:

    const mainWindow = new BrowserWindow(opts)
    remoteMain.enable(mainWindow.webContents);
    mainWindow.webContents.on('will-attach-webview', () => {
      const all = webContents.getAllWebContents();
      all.forEach((item) => {
        remoteMain.enable(item);
     });
    });
  2. When adding a new TAB, set the webPreferences inside webviewAttributes like this:

    ...
    title: "test",
    src: "./test.html",
    webviewAttributes: {
    'nodeintegration': true,
    'contextIsolation': false,
    'webPreferences': 'nodeIntegration=true, contextIsolation=false',
    'preload': "./preLoadTest.js",
    },
    ...

Without setting the 'webPreferences': 'nodeIntegration=true, contextIsolation=false' the @electron/remote won't be able to work even when enabled like before on step 1.

brrd commented 2 years ago

Does anyone know if it's possible and how can we do that?

It's possible but not recommended.

First you have to activate nodeIntegration and disable contextIsolation in browser window.

const mainWindow = new BrowserWindow({
  webPreferences: {
    webviewTag: true,
    contextIsolation: false,
    nodeIntegration: true
  }
})

The when creating the tab, activate nodeintegration in the webview.

const tab = tabGroup.addTab({
  webviewAttributes: { nodeintegration: true }
});

Please note that activating node integration in the renderer process (browser and webview) can be very dangerous, especially when you are manipulating untrusted content in it. The secure way to organize your application is to do all your node stuff in the main process and use IPC to do the communication between processes. More information about this recommendation: https://www.electronjs.org/docs/latest/tutorial/security#2-do-not-enable-nodejs-integration-for-remote-content