开发者

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.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开发者_JAVA技巧 chrome?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜