Javascript 如何使用javascript停止浏览器后退按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12381563/
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-08-23 07:51:22  来源:igfitidea点击:

how to stop browser back button using javascript

javascriptbrowser

提问by Sawant Akshay

I am doing an online quiz app in php. I want to restrict the user from going back in an exam. I have tried the following script but it stops my timer. What should I do?

我正在用 php 做一个在线测验应用程序。我想限制用户返回考试。我尝试了以下脚本,但它停止了我的计时器。我该怎么办?

I have included the source code. The timer is stored in cdtimer.js

我已经包含了源代码。计时器存储在 cdtimer.js 中

<script type="text/javascript">
        window.history.forward();
        function noBack()
        {
            window.history.forward();
        }
</script>
<body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">

I have the exam timer which takes a duration for the exam from a mysqlvalue. The timer starts accordingly but it stops when I put the code in for disabling the back button. What is my problem?

我有一个考试计时器,它从mysql值中获取考试的持续时间。计时器相应地启动,但当我输入禁用后退按钮的代码时它会停止。我的问题是什么?

回答by ColinE

There are numerous reasons why disabling the back button will not really work. Your best bet is to warn the user:

禁用后退按钮不起作用的原因有很多。最好的办法是警告用户:

window.onbeforeunload = function() { return "Your work will be lost."; };

This page does list a number of ways you couldtry to disable the back button, but none are guaranteed:

此页面确实列出了许多您可以尝试禁用后退按钮的方法,但不能保证:

http://www.irt.org/script/311.htm

http://www.irt.org/script/311.htm

回答by Rohit416

It is generally a bad idea overriding the default behavior of web browser.Client side script does not have the sufficient privilege to do this for security reason.

覆盖网络浏览器的默认行为通常是一个坏主意。出于安全原因,客户端脚本没有足够的权限来执行此操作。

There are few similar questions asked as well,

也很少有人问类似的问题,

You can-notactually disable browser back button. However you can do magic using your logic to prevent user from navigating back which will create an impression like it is disabled. Here is how, check out the following snippet.

您实际上无法禁用浏览器后退按钮。但是,您可以使用您的逻辑来实现魔术,以防止用户导航回来,这会产生一种像被禁用的印象。这是方法,请查看以下代码段。

(function (global) { 

    if(typeof (global) === "undefined") {
        throw new Error("window is undefined");
    }

    var _hash = "!";
    var noBackPlease = function () {
        global.location.href += "#";

        // making sure we have the fruit available for juice (^__^)
        global.setTimeout(function () {
            global.location.href += "!";
        }, 50);
    };

    global.onhashchange = function () {
        if (global.location.hash !== _hash) {
            global.location.hash = _hash;
        }
    };

    global.onload = function () {            
        noBackPlease();

        // disables backspace on page except on input fields and textarea..
        document.body.onkeydown = function (e) {
            var elm = e.target.nodeName.toLowerCase();
            if (e.which === 8 && (elm !== 'input' && elm  !== 'textarea')) {
                e.preventDefault();
            }
            // stopping event bubbling up the DOM tree..
            e.stopPropagation();
        };          
    }

})(window);

This is in pure JavaScript so it would work in most of the browsers. It would also disable backspacekey but key will work normally inside inputfields and textarea.

这是纯 JavaScript 编写的,因此可以在大多数浏览器中使用。它还会禁用退格键,但键将在input字段和textarea.

Recommended Setup:

推荐设置:

Place this snippet in a separate script and include it on a page where you want this behavior. In current setup it will execute onloadevent of DOM which is the ideal entry point for this code.

将此代码段放在单独的脚本中,并将其包含在您想要此行为的页面上。在当前设置中,它将执行onloadDOM 事件,这是此代码的理想入口点。

Working DEMO!

工作演示!

Tested and verified in following browsers,

在以下浏览器中测试和验证,

  • Chrome.
  • Firefox.
  • IE (8-11) and Edge.
  • Safari.
  • 铬合金。
  • 火狐。
  • IE (8-11) 和边缘。
  • 苹果浏览器。

回答by vrfvr

<script>
window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";//again because google chrome don't insert first hash into history
window.onhashchange=function(){window.location.hash="no-back-button";}
</script> 

回答by JonBrave

I came across this, needing a solution which worked correctly and "nicely" on a variety of browsers, including Mobile Safari(iOS9 at time of posting). None of the solutions were quite right. I offer the following (tested on IE11, FireFox, Chrome & Safari):

我遇到了这个问题,需要一个在各种浏览器(包括 Mobile Safari(发布时为 iOS9))上都能正常工作且“很好”的解决方案。没有一个解决方案是完全正确的。我提供以下内容(在 IE11、FireFox、Chrome 和 Safari 上测试):

history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event)
{
  history.pushState(null, document.title, location.href);
});

Note the following:

请注意以下事项:

  • history.forward()(my old solution) does not work on Mobile Safari --- it seems to do nothing (i.e. the user can still go back). history.pushState()does work on all of them.
  • the 3rd argument to history.pushState()is a url. Solutions which pass a string like 'no-back-button'or 'pagename'seem to work OK, until you then try a Refresh/Reload on the page, at which point a "Page not found" error is generated when the browser tries to locate a page with that as its Url. (The browser is also likely to include that string in the address bar when on the page, which is ugly.) location.hrefshould be used for the Url.
  • the 2nd argument to history.pushState()is a title. Looking around the web most places say it is "not used", and all the solutions here pass nullfor that. However, in Mobile Safari at least, that puts the page's Url into the history dropdown the user can access. But when it adds an entry for a page visit normally, it puts in its title, which is preferable. So passing document.titlefor that results in the same behaviour.
  • history.forward()(我的旧解决方案)在 Mobile Safari 上不起作用 --- 它似乎什么都不做(即用户仍然可以返回)。history.pushState()确实适用于所有这些。
  • 的第三个参数history.pushState()是一个url。传递类似'no-back-button''pagename'似乎工作正常的字符串的解决方案,直到您尝试在页面上刷新/重新加载,此时当浏览器尝试使用该页面作为其 URL 定位页面时,会生成“找不到页面”错误。(浏览器也可能在页面上的地址栏中包含该字符串,这很丑陋。)location.href应该用于 Url。
  • 的第二个参数history.pushState()title。环顾网络,大多数地方都说它“未使用”,这里的所有解决方案都是null如此。但是,至少在 Mobile Safari 中,这会将页面的 Url 放入用户可以访问的历史记录下拉列表中。但是当它正常为页面访问添加条目时,它会放入其title,这是可取的。因此,通过document.title它会导致相同的行为。

回答by Jeremy Warne

This code will disable the back button for modern browsers which support the HTML5 History API. Under normal circumstances, pushing the back button goes back one step, to the previous page. If you use history.pushState(), you start adding extra sub-steps to the current page. The way it works is, if you were to use history.pushState() three times, then start pushing the back button, the first three times it would navigate back in these sub-steps, and then the fourth time it would go back to the previous page.

此代码将禁用支持 HTML5 History API 的现代浏览器的后退按钮。一般情况下,按后退键后退一步,回到上一页。如果您使用 history.pushState(),您将开始向当前页面添加额外的子步骤。它的工作方式是,如果你使用 history.pushState() 三次,然后开始按下后退按钮,前三次它会在这些子步骤中导航回来,然后第四次它会回到上一页。

If you combine this behaviour with an event listener on the popstateevent, you can essentially set up an infinite loop of sub-states. So, you load the page, push a sub-state, then hit the back button, which pops a sub-state and also pushes another one, so if you push the back button again it will never run out of sub-states to push. If you feel that it's necessary to disable the back button, this will get you there.

如果将此行为与事件上的事件侦听器相结合popstate,您基本上可以设置子状态的无限循环。因此,您加载页面,推送一个子状态,然后点击后退按钮,这会弹出一个子状态并推送另一个子状态,因此如果您再次按下后退按钮,它将永远不会用完要推送的子状态. 如果您觉得有必要禁用后退按钮,这将使您达到目标。

history.pushState(null, null, 'no-back-button');
window.addEventListener('popstate', function(event) {
  history.pushState(null, null, 'no-back-button');
});

回答by Fezal halai

For Restrict Browser back event

对于限制浏览器返回事件

window.history.pushState(null, "", window.location.href);
window.onpopstate = function () {
    window.history.pushState(null, "", window.location.href);
};

回答by Sanchitos

This is the way I could it accomplish it. Weirdly changing the window.location didn't worked out fine in chrome and safari. Happens that the location.hash doesn't create an entry in the history for chrome and safari. So you will have to use the pushstate. This is working for me in all browsers.

这是我可以实现它的方式。奇怪的是,在 chrome 和 safari 中更改 window.location 效果不佳。碰巧 location.hash 不会在历史记录中为 chrome 和 safari 创建条目。所以你将不得不使用pushstate。这在所有浏览器中都适用于我。

    history.pushState({ page: 1 }, "title 1", "#nbb");
    window.onhashchange = function (event) {
        window.location.hash = "nbb";

    };

回答by Eng Mahmoud El Torri

    history.pushState(null, null, location.href);
    window.onpopstate = function () {
        history.go(1);
    };

回答by Ashwin Patil

<html>
<head>
    <title>Disable Back Button in Browser - Online Demo</title>
    <style type="text/css">
        body, input {
            font-family: Calibri, Arial;
        }
    </style>
    <script type="text/javascript">
        window.history.forward();
        function noBack() {
            window.history.forward();
        }
    </script>
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
    <H2>Demo</H2>
    <p>This page contains the code to avoid Back button.</p>
    <p>Click here to Goto <a href="noback.html">NoBack Page</a></p>
</body>
</html>

回答by dav_i

This article on jordanhollinger.comis the best option I feel. Similar to Razor's answer but a bit clearer. Code below; full credits to Jordan Hollinger:

jordanhollinger.com上的这篇文章是我觉得最好的选择。类似于 Razor 的答案,但更清晰一些。代码如下;Jordan Hollinger 的全部功劳:

Page before:

上一页:

<a href="/page-of-no-return.htm#no-back>You can't go back from the next page</a>

Page of no return's JavaScript:

不返回的 JavaScript 页面:

// It works without the History API, but will clutter up the history
var history_api = typeof history.pushState !== 'undefined'

// The previous page asks that it not be returned to
if ( location.hash == '#no-back' ) {
  // Push "#no-back" onto the history, making it the most recent "page"
  if ( history_api ) history.pushState(null, '', '#stay')
  else location.hash = '#stay'

  // When the back button is pressed, it will harmlessly change the url
  // hash from "#stay" to "#no-back", which triggers this function
  window.onhashchange = function() {
    // User tried to go back; warn user, rinse and repeat
    if ( location.hash == '#no-back' ) {
      alert("You shall not pass!")
      if ( history_api ) history.pushState(null, '', '#stay')
      else location.hash = '#stay'
    }
  }
}