javascript 在浏览器窗口关闭之前显示 jQuery 弹出窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10310177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:25:01  来源:igfitidea点击:

Showing a jQuery popup before browser window closes

javascriptjquerypopuponbeforeunload

提问by xmaestro

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

我正在使用以下 js 在浏览器/窗口关闭之前显示一个弹出窗口。但它似乎不起作用。

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

The popup i'm trying to show is prettyPopin. And the #beforecloseis 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.

我要显示的弹出窗口是PrettyPopin。这#beforeclose是我试图在窗口卸载之前绑定点击事件的锚点的 id。我注意到原生 js 弹出窗口有效,但 jQuery 弹出窗口不起作用。

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.

有没有办法实现我想要的?请向我解释或向我推荐相应的链接,因为我不是 js 专家。

Thanks in advance.

提前致谢。

回答by ThiefMaster

You cannot safely do that.

你不能安全地这样做。

onbeforeunloadis 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.

onbeforeunload旨在避免完全阻止用户离开您的页面。您唯一应该做的就是返回一个字符串,其中包含一条消息,说明用户可能不想离开该页面的原因。除非用户使用 firefox ,否则会向用户显示此消息。

回答by Vinod

Try this:

试试这个:

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

        });
</script>

回答by MilkyWayJoe

Try changing it to

尝试将其更改为

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

from jQuery documentation:

来自jQuery 文档

event.preventDefault()

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

event.preventDefault()

说明:如果调用此方法,则不会触发事件的默认动作。

Basically, you are binding the function that shows the popup on the beforeunloadevent, 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.

基本上,您正在绑定在beforeunload事件上显示弹出窗口的函数,但它不会像警报窗口或类似的东西那样阻止浏览器。使用event.preventDefault()您将停止事件流的执行。