Sebastian
Sebastian

Reputation: 87

Electron opening every link in browser instead of electron itself

I wanted to open an external link not in electron but in the browser. Therefore I implemented this code:

document.addEventListener('click', function(event) {
   if (event.target.tagName === 'A' && event.target.href.startsWith('http')) {
   event.preventDefault();
   shell.openExternal(event.target.href);
 }
});

My problem is now that every link that I create, opens in the browser.
e.g.

<a href="http://google.com">foo</a> <-wanted behaviour to open in browser

<a href="#">bar</a> <- not wanted behaviour to open in browser

How can I get it to just open the external link in the browser?

Upvotes: 0

Views: 960

Answers (1)

tpikachu
tpikachu

Reputation: 4844

<a href="#"></a> is actually href="http://localhost:X000/#" so the if condition is always true. Replace your code with this and it should work:

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

    // Create the browser window.
    mainWindow = new BrowserWindow({
      width: 1300,
      height: 800,
    });

    // Load your React app or any other HTML which creates your Electron app content
    mainWindow.loadFile("./build/index.html");

    mainWindow.webContents.on("new-window", function(event, url) {
      event.preventDefault();
      // This will open a new Electron window to load the url.
      shell.openExternal(url);
    });

Upvotes: 0

Related Questions