首页 > 解决方案 > 电子在浏览器中打开每个链接而不是电子本身

问题描述

我想在浏览器中而不是在电子中打开一个外部链接。因此我实现了这段代码:

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

我现在的问题是我创建的每个链接都在浏览器中打开。
例如

<a href="http://google.com">foo</a><-想要在浏览器中打开的行为

<a href="#">bar</a> <- 不希望在浏览器中打开行为

我怎样才能让它在浏览器中打开外部链接?

标签: javascripteventselectron

解决方案


<a href="#"></a>实际上是href="http://localhost:X000/#" 这样 if 条件始终为真。用这个替换你的代码,它应该可以工作:

    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);
    });

推荐阅读