最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to determine if onbeforeunload has been caused by clicking a link in Chrome - Stack Overflow

programmeradmin1浏览0评论

The problem is as follows.

onbeforeunload works like a charm in Firefox and has e.explicitOriginalTarget.activeElementthat shows what element has been clicked to cause it.

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. Is there any way to determine the target in chrome?

The problem is as follows.

onbeforeunload works like a charm in Firefox and has e.explicitOriginalTarget.activeElementthat shows what element has been clicked to cause it.

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. Is there any way to determine the target in chrome?

Share Improve this question edited Sep 21, 2011 at 2:46 pkaeding 37.8k31 gold badges106 silver badges142 bronze badges asked Jan 31, 2010 at 20:25 ZooKeeperZooKeeper 7151 gold badge6 silver badges7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Late response, I know, but you can always try this (confirmed working in 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.

Another option:

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

Then simply refer to last_clicked from within your onbeforeunload handler. This is the best cross-browser patible solution I've found, since document.activeElement is unreliable.

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. 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.

发布评论

评论列表(0)

  1. 暂无评论