使用jQuery / Javascript防止任何形式的页面刷新 [英] Prevent any form of page refresh using jQuery/Javascript

查看:134
本文介绍了使用jQuery / Javascript防止任何形式的页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦用户在我的页面上,我不希望他刷新页面。

Once the user is on my page, I do not want him to refresh the page.


  1. 随时,用户点击 F5 或顶部的刷新按钮。他应该收到警告说

  1. Anytime, the user hits F5 or refresh button on top. He should get an alert saying


您无法刷新页面。

You cannot refresh the page.


  • 此外,如果用户打开一个新标签并尝试访问prev标签中的相同网址,他应该收到提醒

  • Also if the user opens a new tab and tries to access the same url in prev tab he should get an alert


    您无法在2个标签页中打开同一页面

    You cannot open same page in 2 tabs


  • 无论如何,我可以使用JavaScript或jQuery做到这一点?第一点非常重要。

    Anyway I can do this using JavaScript or jQuery? Point one is really important.

    推荐答案

    #1可以通过 window.onbeforeunload

    例如:

    <script type="text/javascript">
        window.onbeforeunload = function() {
            return "Dude, are you sure you want to leave? Think of the kittens!";
        }
    </script>
    

    将提示用户显示该消息,并提供留在页面上或继续保留的选项他们的路。这变得越来越普遍。如果您在键入帖子时尝试离开页面,Stack Overflow会执行此操作。你不能完全阻止用户重新加载,但如果他们这样做,你可以让它听起来真的很可怕。

    The user will be prompted with the message, and given an option to stay on the page or continue on their way. This is becoming more common. Stack Overflow does this if you try to navigate away from a page while you are typing a post. You can't completely stop the user from reloading, but you can make it sound real scary if they do.

    #2或多或少是不可能的。即使您跟踪了会话和用户登录,您仍然无法保证您正确检测到第二个选项卡。例如,也许我打开一个窗口,然后关闭它。现在我打开一个新窗口。您可能会将其检测为第二个选项卡,即使我已经关闭了第一个选项卡。现在您的用户无法访问第一个窗口,因为他们关闭了它,并且他们无法访问第二个窗口,因为您拒绝了它们。

    #2 is more or less impossible. Even if you tracked sessions and user logins, you still wouldn't be able to guarantee that you were detecting a second tab correctly. For example, maybe I have one window open, then close it. Now I open a new window. You would likely detect that as a second tab, even though I already closed the first one. Now your user can't access the first window because they closed it, and they can't access the second window because you're denying them.

    事实上,我银行的在线系统很难做到#2,上述情况一直都在发生。我通常必须等到服务器端会话到期才能再次使用银行系统。

    In fact, my bank's online system tries real hard to do #2, and the situation described above happens all the time. I usually have to wait until the server-side session expires before I can use the banking system again.

    这篇关于使用jQuery / Javascript防止任何形式的页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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