Showing a jQuery popup before browser window closes

淺唱寂寞╮ 提交于 2019-12-24 10:53:26

问题


I'm using the following js to show a popup before the browser/window closes. But it does not seem to be working.

$(window).bind('beforeunload', function(e) {
    $('#beforeclose').click(); 
});

The popup i'm trying to show is prettyPopin . And the #beforeclose is the id of the anchor with which i'm trying to bind the click event before the window unloads. I have noticed that native js popups work but the jQuery popup does not work.

Is there a way to achieve what i want to? Please do explain to me or refer me to the respective link because i'm not an expert at js.

Thanks in advance.


回答1:


You cannot safely do that.

onbeforeunload is designed in a way to avoid completely preventing the user from leaving your page. The only thing you should do is return a string with a message why the user might not want to leave the page. This message is displayed to the user unless he's using firefox.




回答2:


Try this:

<script type="text/javascript">
        $(function() {
        function confirmmsg() {
            return "Mail Not sent";
        }
        window.onbeforeunload = confirmmsg;

        });
</script>



回答3:


Try changing it to

$(window).bind('beforeunload', function(e) {
    $('#beforeclose').click(); 
    e.preventDefault();
    return false; // just in case.. 
});

from jQuery documentation:

event.preventDefault()

Description: If this method is called, the default action of the event will not be triggered.

Basically, you are binding the function that shows the popup on the beforeunload event, but that does not block the browser like an alert window or something like that. Using event.preventDefault() you will stop the execution of event flow.



来源:https://stackoverflow.com/questions/10310177/showing-a-jquery-popup-before-browser-window-closes

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