user2454060
user2454060

Reputation: 91

External image links in Electron do not open in an external browser

I'm using this code to open external links in a browser outside of Electron. It works fine if text is written after the desination :

 let shell = require('electron').shell
document.addEventListener('click', function (event) {
  if (event.target.tagName === 'A' && event.target.href.startsWith('http')) {
    event.preventDefault()
    shell.openExternal(event.target.href)
  }
})

However, if an image is set as the link it doesn't work at all and opens in the Electron browser:

<a href="https://www.stackoverflow.com">
<img src='image1.jpg'></img>
</a>

How can I get an image link to open in an external browser in Electron?

Upvotes: 0

Views: 635

Answers (1)

Andrew Myers
Andrew Myers

Reputation: 2786

The problem here is that you're listening for clicks on the document and then only checking event.target. As you have found out, if the click happens on a child element (for example, an image) inside the link, then event.target points to that child element, and you won't detect that the link was clicked.

This is one of the places jQuery comes in handy. Something like $(document).on('click', 'a', ...) is fairly simple to deal with.

But you don't have to use jQuery. Because Electron uses Chromium, the click events have a non-standard attribute called path. That attribute is an array of parents, going up the DOM, all the way to body, document, and finally global. You can run .find() on this array to check if any element happens to be a link, and then return that link to your event handler to deal with.

Here's what that looks like:

document.addEventListener('click', function(event) {
  const link = getLink(event);

  if (link) {
    event.preventDefault()
    alert('caught: ' + link.href);
  }
});

function getLink(event) {
  return event.path.find(($el) => {
    if ($el.tagName === 'A' && $el.href.startsWith('http')) {
      return true;
    }

    return false;
  });
}
<p>
  Image link:
  <a href="https://www.stackoverflow.com">
    <img src='https://placehold.it/100x100' />
  </a>
</p>

<p>
  Text link:
  <a href="https://example.com">Test link</a>
</p>

Upvotes: 1

Related Questions