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

问题描述 投票:123回答:23

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

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

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

我有考试计时器,它从mysql值开始考试。计时器会相应地启动,但是当我输入代码以禁用后退按钮时它会停止。我的问题是什么?

javascript browser
23个回答
146
投票

禁用后退按钮无法正常工作的原因有很多。您最好的选择是警告用户:

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

此页面列出了许多可以尝试禁用后退按钮的方法,但没有保证:

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


7
投票
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

此JavaScript不允许任何用户返回(适用于Chrome,FF,IE,Edge)


7
投票

对于限制浏览器返回事件

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

5
投票

轻松尝试:

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

3
投票

非常简单和干净的功能,以打破后箭头,而不会干扰页面。

优点:

  • 即时加载并恢复原始哈希,因此用户不会被URL明显改变分心。
  • 用户仍然可以通过向后按10次退出(这是一件好事),但不是偶然的
  • 没有用户干扰像使用onbeforeunload的其他解决方案
  • 它只运行一次,并且在您使用它来跟踪状态时不会干扰进一步的哈希操作
  • 恢复原始哈希,几乎看不见。
  • 使用setInterval所以它不会破坏慢速浏览器并始终有效。
  • 纯Javascript,不需要HTML5历史记录,无处不在。
  • 不引人注目,简单,并与其他代码很好地配合。
  • 不使用unbeforeunload用模态对话框中断用户。
  • 它没有大惊小怪。

注意:其他一些解决方案使用onbeforeunload。请不要将onbeforeunload用于此目的,当用户试图关闭窗口,点击后退等时会弹出一个对话框。像onbeforeunload这样的模态通常只适用于极少数情况,例如当他们实际在屏幕上进行更改时没有救他们,不是为了这个目的。

这个怎么运作

  1. 执行页面加载
  2. 保存原始哈希值(如果在URL中)。
  3. 按顺序将#/ noop / {1..10}附加到哈希
  4. 恢复原始哈希值

而已。没有进一步的混乱,没有背景事件监控,没有别的。

一秒钟使用它

要进行部署,只需将其添加到您的页面或JS中的任何位置:

<script>
/* break back button */                                                                        
window.onload=function(){                                                                      
  var i=0; var previous_hash = window.location.hash;                                           
  var x = setInterval(function(){                                                              
    i++; window.location.hash = "/noop/" + i;                                                  
    if (i==10){clearInterval(x);                                                               
      window.location.hash = previous_hash;}                                                   
  },10);
}
</script>

2
投票

这似乎对我们有用,可以禁用浏览器上的后退按钮,以及退格按钮带你回来。

history.pushState(null, null, $(location).attr('href'));
    window.addEventListener('popstate', function () {
        history.pushState(null, null, $(location).attr('href'));
    });

1
投票
   <script src="~/main.js" type="text/javascript"></script>
    <script type="text/javascript">
        window.history.forward();
        function noBack() { window.history.forward(); } </script>

1
投票

你根本不能也不应该这样做。但是,这可能会有所帮助

<script type = "text/javascript" >
history.pushState(null, null, 'pagename');
window.addEventListener('popstate', function(event) {
history.pushState(null, null, 'pagename');
});
</script>

适用于我的chrome和firefox


1
投票

试试这个以防止IE中的退格按钮默认为“后退”:

<script language="JavaScript">
$(document).ready(function() {
$(document).unbind('keydown').bind('keydown', function (event) {
    var doPrevent = false;


    if (event.keyCode === 8 ) {
        var d = event.srcElement || event.target;
        if ((d.tagName.toUpperCase() === 'INPUT' && 
             (
                 d.type.toUpperCase() === 'TEXT' ||
                 d.type.toUpperCase() === 'PASSWORD' || 
                 d.type.toUpperCase() === 'FILE' || 
                 d.type.toUpperCase() === 'EMAIL' || 
                 d.type.toUpperCase() === 'SEARCH' || 
                 d.type.toUpperCase() === 'DATE' )
             ) || 
             d.tagName.toUpperCase() === 'TEXTAREA') {
            doPrevent = d.readOnly || d.disabled;
        }
        else {

            doPrevent = true;
        }
    }

    if (doPrevent) {
        event.preventDefault();
    }

    try {
        document.addEventListener('keydown', function (e) {
               if ((e.keyCode === 13)){
                  // alert('Enter keydown');
                   e.stopPropagation();
                   e.preventDefault();
               }



           }, true);
        } catch (err) {}
    });
});
</script>

1
投票

我相信完美但解决方案实际上非常简单,我现在使用了很多年。

它基本上是分配窗口的“onbeforeunload”事件以及正在进行的文档“mouseenter”/“mouseleave”事件,因此警报仅在点击位于文档范围之外时触发(然后可以是浏览器的后退或前进按钮)

$(document).on('mouseenter', function(e) { 
        window.onbeforeunload = null; 
    }
);

$(document).on('mouseleave', function(e) { 
        window.onbeforeunload = function() { return "You work will be lost."; };
    }
);

1
投票

在现代浏览器中,这似乎有效:

// https://developer.mozilla.org/en-US/docs/Web/API/History_API
let popHandler = () => {
  if (confirm('Go back?')) {
    window.history.back() 
  } else {
    window.history.forward()
    setTimeout(() => {
      window.addEventListener('popstate', popHandler, {once: true})
    }, 50) // delay needed since the above is an async operation for some reason
  }
}
window.addEventListener('popstate', popHandler, {once: true})
window.history.pushState(null,null,null)

115
投票

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

提出的问题也很少,

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

(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);

这是纯JavaScript,所以它适用于大多数浏览器。它还会禁用退格键,但键将在input字段和textarea内正常工作。

Recommended Setup:

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

Working DEMO!

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

  • 铬。
  • Firefox浏览器。
  • IE(8-11)和Edge。
  • 苹果浏览器。

0
投票

我创建了一个HTML页面(index.html)。我还在(脚本)文件夹/目录中创建了一个(mechanism.js)。然后,我根据需要使用form,table,span和div标签将所有内容放在(index.html)中。现在,这就是让后退/前锋无所作为的伎俩!

首先,你只有一页!其次,使用带有span / div标签的JavaScript可以在需要时通过常规链接隐藏和显示同一页面上的内容!

在'index.html'里面:

    <td width="89px" align="right" valign="top" style="letter-spacing:1px;">
     <small>
      <b>
       <a href="#" class="traff" onClick="DisplayInTrafficTable();">IN</a>&nbsp;
      </b>
     </small>
     [&nbsp;<span id="inCountSPN">0</span>&nbsp;]
    </td>

在'mechanism.js'里面:

    function DisplayInTrafficTable()
    {
     var itmsCNT = 0;
     var dsplyIn = "";
     for ( i=0; i<inTraffic.length; i++ )
     {
      dsplyIn += "<tr><td width='11'></td><td align='right'>" + (++itmsCNT) + "</td><td width='11'></td><td><b>" + inTraffic[i] + "</b></td><td width='11'></td><td>" + entryTimeArray[i] + "</td><td width='11'></td><td>" + entryDateArray[i] + "</td><td width='11'></td></tr>";
     }
     document.getElementById('inOutSPN').innerHTML = "" +
                                             "<table border='0' style='background:#fff;'><tr><th colspan='21' style='background:#feb;padding:11px;'><h3 style='margin-bottom:-1px;'>INCOMING TRAFFIC REPORT</h3>" + DateStamp() + "&nbsp;&nbsp;-&nbsp;&nbsp;<small><a href='#' style='letter-spacing:1px;' onclick='OpenPrintableIn();'>PRINT</a></small></th></tr><tr style='background:#eee;'><td></td><td><b>###</b></td><td></td><td><b>ID #</b></td><td></td><td width='79'><b>TYPE</b></td><td></td><td><b>FIRST</b></td><td></td><td><b>LAST</b></td><td></td><td><b>PLATE #</b></td><td></td><td><b>COMPANY</b></td><td></td><td><b>TIME</b></td><td></td><td><b>DATE</b></td><td></td><td><b>IN / OUT</b></td><td></td></tr>" + dsplyIn.toUpperCase() + "</table>" +
                                             "";
     return document.getElementById('inOutSPN').innerHTML;
    }

它看起来很毛茸茸,但请注意函数名称和调用,嵌入式HTML和span标记id调用。这是为了说明如何在同一页面上将不同的HTML注入相同的span标签!后退/前进如何影响此设计?它不能,因为你隐藏对象并在同一页面上替换其他所有对象!

如何隐藏和显示?这里:根据需要在'mechanism.js'中的内部函数,使用:

    document.getElementById('textOverPic').style.display = "none"; //hide
    document.getElementById('textOverPic').style.display = "";     //display

在'index.html'里面通过链接调用函数:

    <img src="images/someimage.jpg" alt="" />
    <span class="textOverPic" id="textOverPic"></span>

    <a href="#" style="color:#119;font-size:11px;text-decoration:none;letter-spacing:1px;" onclick="HiddenTextsManager(1);">Introduction</a>

我希望我没有让你头疼。对不起,如果我这样做:-)


0
投票

在我的情况下,这是一个购物订单。所以我做的是禁用按钮。当用户单击后,该按钮仍被禁用。当他们再次点击后退,然后点击页面按钮继续前进。我知道他们的订单已提交并跳到另一页。

在页面实际刷新的情况下,按钮(理论上)可用;然后,我能够在页面加载中作出反应,订单已经提交,然后重定向。


0
投票
<script language="JavaScript">
    javascript:window.history.forward(1);
</script>

-1
投票
//"use strict";
function stopBackSpace(e) {
    var ev = e || window.event;
    var obj = ev.target || ev.srcElement;
    var t = obj.type || obj.getAttribute('type');

    var vReadOnly = obj.getAttribute('readonly');
    var vEnabled = obj.getAttribute('enabled');
    // null
    vReadOnly = (vReadOnly == null) ? false : vReadOnly;
    vEnabled = (vEnabled == null) ? true : vEnabled;
    // when click Backspace,judge the type of obj.

    var flag1 = ((t == 'password' || t == 'text' || t == 'textarea') && ((vReadOnly == true || vReadOnly == 'readonly') || vEnabled != true)) ? true : false;

    var flag2 = (t != 'password' && t != 'text' && t != 'textarea') ? true : false;

    if (flag2) {
        e.keyCode = 0;
        e.cancelBubble = true;
        return false;
    }
    if (flag1) {
        e.keyCode = 0;
        e.cancelBubble = true;
        return false;
    }
}
if (typeof($) == 'function') {
    $(function() {
        $(document).keydown(function(e) {
            if (e.keyCode == 8) {
                return stopBackSpace(e);
            }
        });
    });
} else {
    document.onkeydown = stopBackSpace;
}

66
投票
<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> 

57
投票

我遇到了这个问题,需要一个能够在各种浏览器上正常工作并且“很好”的解决方案,包括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);
});

请注意以下事项:

  • history.forward()(我的旧解决方案)无法在Mobile Safari上运行---它似乎什么都不做(即用户仍然可以返回)。 history.pushState()确实对所有这些都有效。
  • history.pushState()的第三个参数是一个网址。传递像'no-back-button''pagename'这样的字符串的解决方案似乎工作正常,直到您在页面上尝试刷新/重新加载,此时浏览器尝试查找具有该页面的页面时会生成“找不到页面”错误网址。 (浏览器也可能在页面上的地址栏中包含该字符串,这很难看。)location.href应该用于Url。
  • history.pushState()的第二个参数是一个标题。环顾网络,大多数地方都说“没有使用”,所有解决方案都通过了null。但是,至少在Mobile Safari中,将页面的Url放入用户可以访问的历史记录下拉列表中。但是当它为正常的页面访问添加一个条目时,它会放入标题,这是更可取的。所以通过document.title导致相同的行为。

25
投票

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

如果将此行为与popstate事件上的事件侦听器结合使用,则实际上可以设置无限循环的子状态。所以,你加载页面,按子状态,然后点击后退按钮,弹出一个子状态,并推动另一个,所以如果你再次按下后退按钮,它将永远不会用完子状态推。如果你认为有必要禁用后退按钮,这将使你到达那里。

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

12
投票

这是我实现它的方式。很奇怪改变wi​​ndow.location在chrome和safari中没有用。发生location.hash不会在chrome和safari的历史记录中创建条目。所以你必须使用pushstate。这适用于所有浏览器。

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

    };

9
投票
<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>

9
投票

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


8
投票

This article on jordanhollinger.com是我觉得最好的选择。与Razor的答案类似,但更清楚一点。代码如下;完全归功于Jordan Hollinger:

页面之前:

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

不归路的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'
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.