Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use Node.js APIs in renderer process

Unable to use any electron or node related operations in electron . Getting error process not defined. I Checked at various places they guide to add node Support but that is already Done so stucked here My Main Application code is

const electron = require("electron");
const { app, BrowserWindow } = electron;

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: { nodeIntegration: true },
  });

  win.loadFile("index.html");
}

app.whenReady().then(createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

And Index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World!</title>
  </head>
  <body style="background: white">
    <h1>Hello World!</h1>
    <p>
      We are using node
      <script>
        document.write(process.versions.node);
      </script>
      , Chrome
      <script>
        document.write(process.versions.chrome);
      </script>
      , and Electron
      <script>
        document.write(process.versions.electron);
      </script>
      .
    </p>
  </body>
</html>
like image 790
vikrant verma Avatar asked Dec 13 '22 07:12

vikrant verma


1 Answers

Update: the answer below is a workaround. You should not disable contextIsolation and you should not enable nodeIntegration. Instead you should use a preload script and the contextBridge API.

In Electron 12, contextIsolation is now by default true

If you set it to false, you will have access to Node.js APIs in the renderer process

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: { 
     contextIsolation: false,
     nodeIntegration: true
    },
  });

  win.loadFile("index.html");
}

⚠️ It's important to note that this is not recommended!

There's a good reason why Electron maintainers changed the default value. See this discussion

Without contextIsolation any code running in a renderer process can quite easily reach into Electron internals or your preload script and perform privileged actions that you don't want arbitrary websites to be doing.

like image 123
aabuhijleh Avatar answered Dec 24 '22 04:12

aabuhijleh