José López
José López

Reputation: 11

Uncaught ReferenceError: require is not defined - Electron js

I'm using electron for the first time at the same time as js and node, I'm trying to make an application for hobby and knowledge. I'm facing a problem when implementing my script to open external links.

I've been using the doc to fix the problem, but I haven't seen anything to help me with that problem.

My ex-links.js

const electron = require("electron");
const { shell } = electron;
const exLinkBtn = document.getElementById("open-ex-link");
exLinkBtn.addEventListener("click", function() {
  shell.openExternal("https://www.youtube.com/watch?v=ifXalt3MJtM");
});

I've already tried to place the slider.html inside index.html and yet I still get that error, so I left it as I currently have it inside an iframe.

<iframe src="slider.html" frameborder=0 width="1180" height="728" style="padding-left:198.5px;"></iframe>

I expect that by clicking the open-ex-link button it will open the link in the default browser.

Upvotes: 1

Views: 1301

Answers (1)

ubuntugod
ubuntugod

Reputation: 652

The default nodeIntegration value is false. So you can set it to true to solve the issue.

app.on('ready', () => {
    mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        }
    });
});

But, nodeIntegration: true is a security risk when you are executing some untrusted remote code on your application. For example, when your application opens up a third party webpage, it would be a security risk because the third party webpage will have access to node runtime and can run malicious code on the user's filesystem. So it makes sense to set nodeIntegration: false which is the default now.

You can use preload scripts as they have access to require and other Node.js features.

The index.js would be like:

const mainWindow = new BrowserWindow({
  webPreferences: {
    preload: path.join(app.getAppPath(), 'preload.js')
  }
})

The preload.js would be like:

const { remote } = require('electron');

let currentWindow = remote.BrowserWindow.getFocusedWindow();

window.closeCurrentWindow = function(){
  currentWindow.close();
}

Upvotes: 1

Related Questions