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

隐身守侯 提交于 2019-12-12 12:18:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26405439/why-ie10-fires-beforeunload-event-when-clicking-on-anchor-element-with-javascrip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!