5

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?

pkaeding
  • 36,513
  • 30
  • 103
  • 141
ZooKeeper
  • 685
  • 1
  • 6
  • 7

3 Answers3

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.

pkaeding
  • 36,513
  • 30
  • 103
  • 141
SegaAges
  • 51
  • 1
  • 2
2

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.

Damien Roche
  • 13,189
  • 18
  • 68
  • 96
  • Adding a timer gives you even more certainty that it really was a click. See: http://stackoverflow.com/a/25037876/1784062 – joost Jul 30 '14 at 13:19
  • document.activeElement is unreliable ? – Kiquenet Dec 11 '18 at 16:34
  • I wish I had made a note, as this is hard to remember why after almost 5 years. I suspect I was being returned an element I did not expect through `document.activeElement`, but this could very well have been due to not understanding how the elements layered each other -- sometimes it's `a`, sometimes in `i`, why? Because I'm clicking the icon which is wrapped in the link. Not sure if `activeElement` still does that or ever did in differing browsers. Someone commented in 2015 on another answer that it didn't work in Safari. Support across the board has likely improved. – Damien Roche Dec 11 '18 at 17:52
0

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.

Tim Down
  • 318,141
  • 75
  • 454
  • 536