How can I force external links from browser-window to open in a default browser from Electron?
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.
Improved from the accepted answer ;
- the link must be
target="_blank"
; 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.