Search code examples
javascriptonclickevent-handlingdom-eventspage-refresh

How to prevent `tel:` links from firing a `beforeunload` event?


I have a popup appear before the user refreshes the page by doing this:

window.addEventListener('beforeunload', function (e) {
  e.preventDefault();
  e.returnValue = '';
});

This is working as expected, but I don't want the popup to appear after the user clicks a tel: link, like <a href="tel:123123123">phone number</a> for example.

I was thinking I could detect a click on all the tel: links like so:

const phoneLinks = document.querySelectorAll('a[href^="tel:"]');
phoneLinks.forEach((phoneLink) => {
  phoneLink.addEventListener('click', () => {
    // Not sure what I can do
  });
});

I have a codepen set up for this, but I'm not sure how to actually solve the problem: https://codepen.io/obliviga/pen/XWxYJQG

Anyone have any ideas?


Solution

  • Add a target attribute to the links, so they open in a new window.

    phoneLinks.forEach(link => link.addAttribute('target', '_blank'))