为什么IE10在使用javascript href单击anchor元素时触发beforeunload事件以及如何防止它 [英] Why IE10 fires beforeunload event when clicking on anchor element with javascript href and how to prevent it

查看:114
本文介绍了为什么IE10在使用javascript href单击anchor元素时触发beforeunload事件以及如何防止它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了跟踪用户何时离开页面,我们会先听取 beforeunload 事件。一切正常,直到用户使用 IE10 ,用 href 参数中的javascript点击空链接(锚点)而不是网址。例如:

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>

此案例使IE10 有时触发 beforeunload 事件。 Chrome / IE11工作正常(0 beforeunload s),而IE10会不时触发它,特别是如果你快速点击它。这是 JSFiddle 来试试。

任何人都知道它为什么会发生以及如何解决它?我很乐意在标记中删除/替换这样的锚点,但在我的情况下是不可能的。

谢谢。

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.

推荐答案

从技术上讲,IE10可能被认为是正确的,因为你正在卸载页面......那种。如果你的链接是:

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';">

然后你最终会出现一个只有内容'blah'的新页面。这是 javascript:链接工作的方式。 void 什么都不返回( undefined ),当 javascript:链接返回任何内容然后它不会替换页面内容。

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.

理论上,如果目标资源是下载的话,类似的事情会发生 - 页面通常是卸载但因为目标是下载,页面不会更改。并且 204 No Content 的HTTP响应也应该触发此行为。

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.

据我所知,唯一真正的解决办法是确保你正确 preventDefault 你的点击事件。

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

这篇关于为什么IE10在使用javascript href单击anchor元素时触发beforeunload事件以及如何防止它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆