3

I want to open an iframe link in a browser using electron. I found some solutions but they are not working, here are examples I tried:

I think the problem is, that the link is in the scr Tag.

Looking for a possible solution why nothing is working

Here is an example iframe element

<iframe src="https://rcm-eu.amazon-adsystem.com/e/cm?o=3&p=48&l=ur1&category=channels&banner=138WWDCBD6MQJVWGMHG2&f=ifr&linkID=0335593f7b48da8f8d1dab568039dc08&t=adrgoe-21&tracking_id=adrgoe-21" width="728" height="90" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>

And here is my Electron code

const shell = require('electron').shell;

// assuming $ is jQuery
$(document).on('click', 'a[href^="http"]', function(event) {
    event.preventDefault();
    shell.openExternal(this.href);
});
Fraser
  • 15,275
  • 8
  • 53
  • 104
Adrian
  • 135
  • 1
  • 3
  • 12

3 Answers3

1

I found a solution. I changed the iframe to a webview:

<webview id="webview" src="https://stackoverflow.com/" nodeintegration></webview>

The JS is now:

const {shell} = require('electron')
const webview = document.querySelector('webview')
webview.addEventListener('will-navigate', (e) => {
  const protocol = require('url').parse(e.url).protocol
  if (protocol === 'http:' || protocol === 'https:') {
    shell.openExternal(e.url)
  }
});

Instead of 'will-navigate' you can choose different actions. Find the all here

webview.addEventListener('will-navigate', (e) => {

Now I have to find out, how to stop change the page in the webview. But it open the link in the default browser.

Adrian
  • 135
  • 1
  • 3
  • 12
0

You are detecting clicks on a[href^="http"] but your tag is an iframe

Really you should give the iframe an id or something then handle your click targeting it. e.g.

<iframe id="myframe" src="...></iframe>

and

const shell = require('electron').shell;

// assuming $ is jQuery
$(document).on('click', 'a[href^="http"]', function(event) {
    event.preventDefault();
    var iframe = document.getElementById('myframe')
    console.log(iframe, event.target) // what are these?
    if(iframe) {
       shell.openExternal(iframe.href);
    }
});
Fraser
  • 15,275
  • 8
  • 53
  • 104
  • I tried to use the code and tried a few things on it. But I do not get it that the link in a standard browser is opened. – Adrian Aug 29 '17 at 07:21
0

If I understand the threads on github one way to do this is to use a <webview> instead of an <iframe>. Then put code like this in your main.js/browser process NOT the renderer process

app.on('web-contents-created', (event, contents) => {
  if (contents.getType() === 'webview') {
    contents.on('will-navigate', (event, url) => {
      event.preventDefault();
      shell.openExternal(url);
    });
  }
});

Putting code in the renderer process won't work, at least as of Electron 1.8.4

gman
  • 100,619
  • 31
  • 269
  • 393