如何阻止页面在 JS 中卸载(导航)? [英] How do I stop a page from unloading (navigating away) in JS?

查看:25
本文介绍了如何阻止页面在 JS 中卸载(导航)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何阻止页面重新加载或导航吗?

Does anyone know how to stop a page from reloading or navigating away?

jQuery(function($) {

    /* global on unload notification */
    warning = true;

    if(warning) {
        $(window).bind("unload", function() { 
            if (confirm("Do you want to leave this page") == true) {
                //they pressed OK
                alert('ok');
            } else {
                // they pressed Cancel
                alert('cancel');
                return false;
            }
        });
    }
});

我目前在一个电子商务网站上工作,显示您未来订单的页面可以使用 +/- 按钮更改订购的商品数量.以这种方式更改数量实际上并不会更改订单本身,他们必须按确认并因此采取积极行动来更改订单.

I am working on an e-commerce site at the moment, the page that displays your future orders has the ability to alter the quantities of items ordered using +/- buttons. Changing the quantities this way this doesn't actually change the order itself, they have to press confirm and therefore committing a positive action to change the order.

但是,如果他们更改了数量并离开页面,我想警告他们他们会这样做,以防万一这是意外,因为如果他们离开或刷新页面,更改后的数量将会丢失.

However if they have changed the quantities and navigate away from the page I would like to warn them they are doing so in case this is an accident, as the changed quantities will be lost if they navigate away or refresh the page.

在上面的代码中,我使用了一个全局变量,默认情况下它是假的(只有在测试时才为真),当数量发生变化时,我会将此变量更新为真,当他们确认更改时,我将设置它是假的.

In the code above I am using a global variable which will be false by default (its only true for testing), when a quantity is changed I will update this variable to be true, and when they confirm the changes I will set it to false.

如果警告是真的并且页面被卸载,我会向他们提供一个确认框,如果他们说不,他们想留在这个页面上,我需要阻止它卸载.return false 不起作用,它仍然让用户导航(警报仅用于调试)

If warning is true and the page is unloaded, I offer them a confirmation box, if they say no they would like to stay on this page I need to stop it from unloading. return false isn't working, it still lets the user navigate away (the alerts are there for debugging only)

有什么想法吗?

推荐答案

onbeforeunload 就是你想要的;您的函数应该为 Event 对象的 returnValue 属性分配一个字符串值并返回相同的字符串".检查来自 MicrosoftMozilla 了解详情.

onbeforeunload is the one you want; your function "should assign a string value to the returnValue property of the Event object and return the same string". Check the docs from Microsoft and Mozilla for details.

浏览器将使用您返回的字符串向用户显示自定义确认框,允许他们选择拒绝留在那里.必须这样做以防止恶意脚本导致拒绝浏览器攻击.

The string you return will be used by the browser to present the user with a custom confirm box, allowing them to refuse to stay there if they so choose. It has to be done that way to prevent malicious scripts causing a Denial-of-Browser attack.

这篇关于如何阻止页面在 JS 中卸载(导航)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆