Electron: How to prevent navigation on webview when a URL link is clicked

Created on 22 Jan 2016  ·  3Comments  ·  Source: electron/electron

Hi,
I looked into the following sentence in will-navigate event (https://github.com/atom/electron/blob/master/docs/api/web-view-tag.md) documentation.

Calling event.preventDefault() does NOT have any effect.

So how can we prevent webview from navigating to other page? I intent to launch default browser when user clicks on a URL link on webview.
Here is my code on the renderer process.

 webview.addEventListener('will-navigate', function(e) {
        e.preventDefault();
        require('electron').shell.openExternal(e.url);
 });

With this code, when I click the URL link on webview, webview will navigate to the new page and default browser also opened showing the new page. I want webview to stop navigating to the new page.

Most helpful comment

this works for me for preventing navigation via user clicking on links and notifying the app about the requested url. Using preload and injecting this:

document.addEventListener('DOMContentLoaded', function () {
  document.addEventListener('click', function (e) {
    e.preventDefault();
    e.stopPropagation();
    setTimeout(function () {
      var path = e.target.href;
      ipcRenderer.sendToHost('element-clicked', path);
    }, 100);
    return false;
  }, true);
});

please note the 3rd param at the document.addEventListener('click', fn, true)

ref: https://stackoverflow.com/questions/6157486/jquery-trap-all-click-events-before-they-happen/6157660#6157660

All 3 comments

Duplicate of #1378.

I don't see a solution posted?

this works for me for preventing navigation via user clicking on links and notifying the app about the requested url. Using preload and injecting this:

document.addEventListener('DOMContentLoaded', function () {
  document.addEventListener('click', function (e) {
    e.preventDefault();
    e.stopPropagation();
    setTimeout(function () {
      var path = e.target.href;
      ipcRenderer.sendToHost('element-clicked', path);
    }, 100);
    return false;
  }, true);
});

please note the 3rd param at the document.addEventListener('click', fn, true)

ref: https://stackoverflow.com/questions/6157486/jquery-trap-all-click-events-before-they-happen/6157660#6157660

Was this page helpful?
0 / 5 - 0 ratings

Related issues

EladBezalel picture EladBezalel  ·  3Comments

diracdeltas picture diracdeltas  ·  3Comments

lealife picture lealife  ·  3Comments

rhnorskov picture rhnorskov  ·  3Comments

etiktin picture etiktin  ·  3Comments