Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access JavaScript href event that triggered beforeunload

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?

like image 794
David Cook Avatar asked Dec 04 '22 02:12

David Cook


1 Answers

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>
like image 162
chucksmash Avatar answered Jan 11 '23 17:01

chucksmash