How to access JavaScript href event that triggered beforeunload

主宰稳场 提交于 2019-11-30 17:41:46

问题


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?


回答1:


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>



回答2:


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();
        }
    }
}


来源:https://stackoverflow.com/questions/12065389/how-to-access-javascript-href-event-that-triggered-beforeunload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!