简体   繁体   English

如何确定点击Chrome中的链接是否导致onbeforeunload

[英]How to determine if onbeforeunload has been caused by clicking a link in Chrome

The problem is as follows. 问题如下。

onbeforeunload works like a charm in Firefox and has e.explicitOriginalTarget.activeElement that shows what element has been clicked to cause it. onbeforeunload就像在Firefox中的魅力一样,并且有e.explicitOriginalTarget.activeElement ,它显示了被点击的元素。

window.onbeforeunload = function(e){
if (e.explicitOriginalTarget.activeElement){
    return;
}

In Chrome the ' e ' object looks identical when you close the window or click the link. 在Chrome中,当您关闭窗口或单击链接时,“ e ”对象看起来完全相同。 Is there any way to determine the target in chrome? 有没有办法确定chrome中的目标?

Late response, I know, but you can always try this (confirmed working in IE): 迟到的反应,我知道,但你总是可以尝试这个(确认在IE中工作):

target = document.activeElement;
alert(target.href);

Just showing you that you can grab the active element and then just parse the href to figure out what is happening. 只是告诉你,你可以抓住活动元素,然后解析href来弄清楚发生了什么。

Another option: 另外一个选项:

$("a").on("click", function(){
  window.last_clicked = $(this);
});

Then simply refer to last_clicked from within your onbeforeunload handler. 然后简单地从onbeforeunload处理程序中引用last_clicked This is the best cross-browser compatible solution I've found, since document.activeElement is unreliable. 这是我发现的最佳跨浏览器兼容解决方案,因为document.activeElement不可靠。

No. The target of the event is the window or document, not the link. 不。事件的目标是窗口或文档,而不是链接。 Unlike Firefox, Chrome provides no helpful bonus properties on the event object. 与Firefox不同,Chrome在事件对象上没有提供有用的奖励属性。 Your best bet may be to have an click event handler on the body that examines the event target to see if it's a link, but that's not foolproof: the link may have its own click event handler that prevents the default action, or the user may follow the link using the keyboard, in which case no click event will be fired. 你最好的选择可能是在主体上有一个点击事件处理程序来检查事件目标,看它是否是一个链接,但这不是万无一失的:链接可能有自己的点击事件处理程序,可以阻止默认操作,或者用户可能使用键盘关注链接,在这种情况下不会触发任何点击事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM