How can I get the destination URL for the onbeforeunload event?

JavascriptUrlDom EventsOnunload

Javascript Problem Overview


I've searched for hours, but I couldn't find a solution for this.

window.onbeforeunload = warn;

This doesn't work:

function warn (e) 
{ 
   var destination = e.href;
   alert(destination );
}

Okay, so to clear the things. If the user clicks on a link on the page itself, it is easy, because you can add an eventhandler to all of the links onclick event, but. I want to catch the address, what the user types into the url box of the browser.

Javascript Solutions


Solution 1 - Javascript

Because it can't be done. The new location is private/sensitive information. Nobody wants you to know which sites they visit when they leave your site.

Solution 2 - Javascript

If you just want to see what link destination, you can use :

document.activeElement.href 

But getting the address line destination is not possible.

I've heard of solutions where they fire off an event if the mouse moves up to the address line (to warn the user that there are unfinished processes that have not been dealt with), but this sort of hack I would never do.

Solution 3 - Javascript

Kaze's answer is an interesting approach, but looking at the element focus when the page is navigated away from isn't really reliable. Partly because there is a delay between the link click and the navigation away from the page (during which time the user may move focus to some other element, but also because a link may be focused (eg. by keyboard control, or mousedown-without-click) without actually being used to navigate away from the page. So if you focused a link then closed the window, it'd think you were following the link.

Trapping onclick for every link on the page (plus onsubmit on every form) is slightly more reliable, but can still be fooled due to the delay. For example you click a link, but then before the new page starts loading hit the back button (or press Escape). Again, if you close the window it thinks you're following the link.

> I want to catch the address, what the user types into the url box of the browser.

There is no way that will ever happen. It is an obvious privacy no-no.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmisnyoView Question on Stackoverflow
Solution 1 - JavascriptMichel van EngelenView Answer on Stackoverflow
Solution 2 - JavascriptEspen SchulstadView Answer on Stackoverflow
Solution 3 - JavascriptbobinceView Answer on Stackoverflow