Fire onbeforeunload confirm alert for external sites only

爷,独闯天下 提交于 2019-12-02 06:50:20

问题


I am using window.onbeforeunload method to show confirm message if user leaves website.

window.onbeforeunload = function(e) {
    return textMsg;
};

But I need this to be fired only if user navigates to external web-site or closes window.

So how to cancel this confirm message for all XHR inside same domain and form submit etc?


回答1:


Try (untested code):

window.onbeforeunload = function(e) {
    return textMsg;
};

$('a:not([href^="http"])').on('click', function() {
    window.onbeforeunload = null; // prevent message
});

$('form').on('submit', function() {
    window.onbeforeunload = null; // prevent message
});

This will prevent the event from triggering if links do not start with http (external links) and for <form> submits. Looking for a solution for window closing at the moment.



来源:https://stackoverflow.com/questions/29408083/fire-onbeforeunload-confirm-alert-for-external-sites-only

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