1

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.

José López
  • 11
  • 1
  • 4
  • 1
    The first thing that looks strange to me is that this looks like your client side app. In which case, I'm not 100% sure `require` will work in the browser. Have you tried using `import` instead? – mwilson Aug 04 '19 at 01:19
  • Check this out: https://github.com/electron/electron/issues/17241 too – mwilson Aug 04 '19 at 01:21
  • @mwilson I'm trying to make it just in the client side , does it affect ? , this is my [main.js](https://pastebin.com/EeZ04KTQ) – José López Aug 04 '19 at 02:18
  • Possible duplicate of [Electron require() is not defined](https://stackoverflow.com/questions/44391448/electron-require-is-not-defined) – Puka Aug 25 '19 at 08:54

1 Answers1

1

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();
}
ubuntugod
  • 592
  • 7
  • 16