How to access JavaScript href event that triggered beforeunload
Asked Answered
T

2

4

I would like to access the event that caused a beforeunload event. Specifically, if I click on a link to another page, I would like to know what the link was in the beforeunload event handler.

In this way, I would be perform different actions in the beforeunload event handler according to what the URL was.

Eg 'http:' or 'https:' warn user about losing unsaved changes; 'mailto:' or 'skype:' don't warn user because page is not actually going to be unloaded.

I am trying to build a good solution to a problem like this: mailto link (in chrome) is triggering window.onbeforeunload - can i prevent this?

Tenishatenn answered 22/8, 2012 at 1:53 Comment(0)
B
17

I was all prepared to tell you this was impossible because the onbeforeunload event only reports to have been triggered by the window when you check out event.target, event.originaltarget, etc. If you override window.onclick, however, we can modify that method to register which element was last clicked on the page. Then, by providing code for window.onbeforeunload, we can specify new behavior that will check for the href of the element which was clicked last. Hooray, beer!

Here's code that will give you exactly the information you want though, in pure javascript and with no cruft to add inside your anchor tags. I've also thrown in the preventDefault() which will pop up the "This page is asking you to confirm that you want to leave - data you have entered may not be saved." confirm box. Hope this helps - you can figure out what to do from here.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>12065389</title>
    <meta charset="utf-8">
    <script type="text/javascript">
        var last_clicked;

        window.onclick = function(e) {
            last_clicked = e.target;
            return true;
        }

        window.onbeforeunload = function(e) {
            var e = e || window.event;
            if (last_clicked.href) {
                alert(last_clicked.href);
                e.preventDefault();
            }
        }
   </script>
</head>
<body>
<a href="http://google.com">google</a>
</body>
</html>
Bindery answered 22/8, 2012 at 2:53 Comment(0)
S
1

I would probably attach the event to all links on the page, rather than the beforeunload event.

Something like:

$("a").click(function(evt) {
    if($(this).attr('href').indexOf('http') == 0) {
        if(confirm("Are you sure?")) {
            //continue
        } else {
            evt.preventDefault();
        }
    }
}
Silicify answered 22/8, 2012 at 2:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.