How to determine if onbeforeunload is caused by clicking a link in Chrome

The problem is as follows.

onbeforeunload works like a charm in Firefox and has an e.explicitOriginalTarget.activeElement that shows which item was clicked to trigger it.

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

In Chrome, the ' e ' object looks identical when you close a window or click a link. Is there a way to determine the target in chrome?

+4
source share
3 answers

Not. The purpose of the event is a window or document, not a link. Unlike Firefox, Chrome does not provide any useful bonus properties for an event object. It’s best if you have a click event handler on the body that examines the purpose of the event to see if it is a link, but it is not reliable: the link can have its own click event handler, which prevents the default action, or the user can follow the link using the keyboard, in which case the click event will not be fired.

0
source

Late answer, I know, but you can always try this (confirmed to work in IE):

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

Just by showing that you can capture the active element and then just analyze the href to find out what is happening.

+5
source

Another option:

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

Then just refer to last_clicked from your onbeforeunload handler. This is the best cross browser compatible solution I have found since document.activeElement is unreliable.

+2
source

Source: https://habr.com/ru/post/1299895/


All Articles