user1679669
user1679669

Reputation: 352

Electron: Prevent middle click

In Electron, it is possible to use the following to open links in the web browser and not in Electron with left click:

const {shell} = require('electron')
function openUrl(e) {
    var e = window.e || e;
    if (e.target.localName == 'a') {
        e.preventDefault();
        shell.openExternal(e.target.href);
    }
}
window.addEventListener('click', openUrl, false);

However, click does not work for middle mouse button. mousedown and mouseup open the link in both a new Electron window and in the web browser (probably because it fires after a new Electron window is created).

How do I stop a link opening a new Electron window with middle click in Electron?

Upvotes: 2

Views: 3052

Answers (1)

Hans Koch
Hans Koch

Reputation: 4481

You've got to use auxclick (https://developer.mozilla.org/en-US/docs/Web/Events/auxclick) it handles all non-left clicks and is the key event for creating the electron window via middle mouse. This code is for the render process within a preload script or enabled nodeIntegration

const { shell } = require('electron')

function auxclickHandler(event) {
    if (e.target.localName == 'a') {
        event.preventDefault();
        shell.openExternal(url);
    }
}

document.addEventListener('auxclick', callback, false)

An alternative if you want to redirect any type of link to the internal browser. This code is for the main process

Here a fiddle for Electron Fiddle https://gist.github.com/Hammster/ce4fac29deaf3600665d9534e3a32317

const { shell } = require('electron')

mainWindow.webContents.on('new-window', function (event, url) {
    event.preventDefault()
    shell.openExternal(url)
})

Upvotes: 6

Related Questions