How can I force external links from browser-window to open in a default browser from Electron?

后端 未结 9 1007
猫巷女王i
猫巷女王i 2020-12-13 06:10

I\'m using the BrowserWindow to display an app and I would like to force the external links to be opened in the default browser. Is that even possible or I have to approach

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 06:26

    I haven't tested this but I assume this is should work:

    1) Get WebContents of the your BrowserWindow

     var wc = browserWindow.webContents;
    

    2) Register for will-navigate of WebContent and intercept navigation/link clicks:

    wc.on('will-navigate', function(e, url) {
      /* If url isn't the actual page */
      if(url != wc.getURL()) {
        e.preventDefault();
        openBrowser(url);
      } 
    }
    

    3) Implement openBrowser using child_process. An example for Linux desktops:

    var openBrowser(url) {
      require('child_process').exec('xdg-open ' + url);
    }
    

    let me know if this works for you!

提交回复
热议问题