Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why IE10 fires beforeunload event when clicking on anchor element with javascript href and how to prevent it

In order to track when user leaves the page, we listen to beforeunload event. Everything works fine until user, that uses IE10, clicks on empty link (anchor) with javascript in href parameter instead of url. For example:

<a href="javascript:void(0)">Empty link with JS in href</a>

This case makes IE10 sometimes fire beforeunload event. Chrome/IE11 work fine (0 beforeunloads), while IE10 fires it from time to time, especially if you click it fast. Here is JSFiddle to try it.
Does anyone know why does it happen and how to fix it? I would be happy to remove/replace such anchors in mark-up, but it is impossible in my case.
Thanks.

like image 877
Eadel Avatar asked Mar 18 '23 04:03

Eadel


1 Answers

Technically, IE10 may be considered correct to do so because you are unloading the page... kind of. If your link were:

<a href="javascript:'blah';">

Then you would end up on a new page with just the content 'blah'. This is how javascript: links work. void returns nothing (undefined), and when a javascript: link returns nothing then it does not replace the page contents.

A similar thing would happen, in theory, if the target resource is a download - the page would normally be unloaded but because the target is a download, the page does not change. And HTTP response of 204 No Content should also trigger this behaviour.

However, as you have noticed, this is undesirable behaviour and so it has become more common to see that the browser will not trigger an unload event until the page itself really is being unloaded. Unfortunately, this is a browser-level thing and outside your control, as far as I'm aware.

To my knowledge the only real fix for this would be to ensure you are properly preventDefaulting your click event.

like image 96
Niet the Dark Absol Avatar answered Mar 26 '23 03:03

Niet the Dark Absol