[英]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. 为了跟踪用户何时离开页面,我们会收听
beforeunload
事件。 Everything works fine until user, that uses IE10
, clicks on empty link (anchor) with javascript in href
parameter instead of url. 一切正常,直到用户使用
IE10
,用href
参数中的javascript而不是url点击空链接(锚点)。 For example: 例如:
<a href="javascript:void(0)">Empty link with JS in href</a>
This case makes IE10 sometimes fire beforeunload
event. 这种情况使IE10 有时会在
beforeunload
事件之前触发。 Chrome/IE11 work fine (0 beforeunload
s), while IE10 fires it from time to time, especially if you click it fast. Chrome / IE11工作正常(0前
beforeunload
),而IE10会不时触发,特别是如果你快速点击它。 Here is JSFiddle to try it. 这是JSFiddle尝试它。
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. 谢谢。
Technically, IE10 may be considered correct to do so because you are unloading the page... kind of. 从技术上讲,IE10可能被认为是正确的,因为你正在卸载页面...有点。 If your link were:
如果您的链接是:
<a href="javascript:'blah';">
Then you would end up on a new page with just the content 'blah'. 然后你最终会在一个只有内容'blah'的新页面上。 This is how
javascript:
links work. 这就是
javascript:
links的工作原理。 void
returns nothing ( undefined
), and when a javascript:
link returns nothing then it does not replace the page contents. void
返回任何内容( undefined
),当javascript:
link返回任何内容时,它不会替换页面内容。
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. 并且
204 No Content
HTTP响应也应该触发此行为。
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 preventDefault
ing your click event. 据我所知,唯一真正的解决方法是确保您正确防止
preventDefault
您的点击事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.