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

后端 未结 9 1000
猫巷女王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:39

    Improved from the accepted answer ;

    1. the link must be target="_blank" ;
    2. add in background.js(or anywhere you created your window) :

      window.webContents.on('new-window', function(e, url) {
        // make sure local urls stay in electron perimeter
        if('file://' === url.substr(0, 'file://'.length)) {
          return;
        }
      
        // and open every other protocols on the browser      
        e.preventDefault();
        shell.openExternal(url);
      });
      

    Note : To ensure this behavior across all application windows, this code should be run after each window creation.

    0 讨论(0)
  • 2020-12-13 06:40

    I solved the problem by the following step

    1. Add shell on const {app, BrowserWindow} = require('electron')
    const {app, BrowserWindow, shell} = require('electron')
    
    
    1. Set nativeWindowOpen is true
    function createWindow () {
      // Create the browser window.
      const mainWindow = new BrowserWindow({
        width: 1350,
        height: 880,
        webPreferences: {
          nativeWindowOpen: true,
          preload: path.join(__dirname, 'preload.js')
        },
        icon: path.join(__dirname, './img/icon.icns')
    })
    
    1. Add the following listener code
      mainWindow.webContents.on('will-navigate', function(e, reqUrl) {
        let getHost = url=>require('url').parse(url).host;
        let reqHost = getHost(reqUrl);
        let isExternal = reqHost && reqHost !== getHost(wc.getURL());
        if(isExternal) {
          e.preventDefault();
          shell.openExternal(reqUrl, {});
        }
      })
    

    reference https://stackoverflow.com/a/42570770/7458156 by cuixiping

    0 讨论(0)
  • 2020-12-13 06:48

    I came up with this, after checking the solution from the previous answer.

    mainWindow.webContents.on('new-window', function(e, url) {
      e.preventDefault();
      require('electron').shell.openExternal(url);
    });
    

    According to the electron spec, new-window is fired when external links are clicked.

    NOTE: Requires that you use target="_blank" on your anchor tags.

    0 讨论(0)
提交回复
热议问题