【问题标题】:How can I stop the browser back button using JavaScript?如何使用 JavaScript 停止浏览器后退按钮?
【发布时间】:2016-10-22 22:05:12
【问题描述】:

我正在用 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


【解决方案1】:

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

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

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

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

【讨论】:

  • 如果答案已经提交,您应该检查您的 PHP 代码,如果已经提交,则拒绝它。
  • 值得一提的是,现代浏览器现在发生了变化:见stackoverflow.com/questions/19926641/…
  • 它可以工作,但是,这也会在所有菜单按钮上显示警报。当它要更改页面时,它会显示警报。我们可以只将它修复到后退按钮吗
【解决方案2】:

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

也有人问了一些类似的问题,

不能实际上禁用了浏览器的后退按钮。但是,您可以使用您的逻辑来做魔术,以防止用户向后导航,这将产生一种好像它被禁用的印象。方法如下 - 查看以下 sn-p。

(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 the event bubbling up the DOM tree...
            e.stopPropagation();
        };
    }
})(window);

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

推荐设置:

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

Working DEMO!

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

  • 铬。
  • 火狐。
  • Internet Explorer (8-11) 和 Edge。
  • Safari。

【讨论】:

  • 我不明白为什么 setTimeout。如果我最初只是附加 #!定位并删除 setTimeout,它仍然有效。
  • 是的,它会起作用,但如果我必须从记忆中回忆起一些东西,当我首先想到这个时......流程在 chrome 中无法像在其他浏览器中那样正常工作。 Chrome 最初返回了空的location.hash,所以它让我这样做了。可能会有更多改进,但 50 毫秒一次并没有花费我太多,所以我把它留在那里。
  • 哦,这是一个内存挑战,谢谢 :) 我使用了你的解决方案,但是用 .onhashchange 处理程序替换了 setInterval。完美运行。但是我还有另一个问题:为什么要“if(global.location.hash!= _hash)”?我认为这种情况只能一直为真,因为 window.location.hash 应该始终返回带有“#”字符的哈希,而 _hash 永远不会包含“#”字符。你还记得那件事吗?如果浏览器不返回 location.hash 中的 '#' 字符,这是否只是一种保护?
  • 我按照建议创建了一个 .js 文件,并使用以下代码将 js 文件包含在我的代码中: 但我仍然可以执行返回(使用 Safari)。我错过了什么?这个库的添加方式与我使用的其他库相同,因此包含很好。
  • 阻止 ipad air、ios 8 上的后退按钮
【解决方案3】:

我遇到了这个问题,需要一个在各种浏览器上都能正常工作且“很好”的解决方案,包括 Mobile Safari(发布时为 iOS 9)。没有一个解决方案是完全正确的。我提供以下服务(在 Internet Explorer 11、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() 的第三个参数是一个 url。传递'no-back-button''pagename' 之类的字符串的解决方案似乎可以正常工作,直到您尝试在页面上刷新/重新加载,此时当浏览器尝试定位页面时会生成“找不到页面”错误以它作为它的 URL。 (浏览器在页面上时也可能在地址栏中包含该字符串,这很难看。)location.href 应该用于 URL。
  • history.pushState() 的第二个参数是一个标题。环顾网络,大多数地方都说它“未使用”,这里的所有解决方案都为此通过null。但是,至少在 Mobile Safari 中,这会将页面的 URL 放入用户可以访问的历史下拉列表中。但是当它正常添加一个页面访问的条目时,它会放入它的title,这是更可取的。因此,为此传递 document.title 会导致相同的行为。

【讨论】:

  • 这是正确答案。在 Chrome、IE 11、Firefox 和 Edge 上完美运行。
  • 这应该是公认的答案,它是跨平台的,而且工作正常。
  • 现代浏览器的完美解决方案。我已经结合@Rohit416 回答来支持旧版浏览器,只使用条件 typeof (history.pushState) === "function" 工作顺利。
  • 在 Chrome 79.0.3945.130 这对我不起作用。我完全按照上面的方式实现,我可以通过单击“后退”按钮返回。当我按住“后退”按钮并选择历史记录中的任何项目时,我确实被阻止了。但是快速单击“后退”按钮会将我带回到上一页。
  • 此解决方案在 Chrome 中不起作用。在其他浏览器中工作。我不知道为什么它不再适用于 Chrome。这是一种可疑的做法,这让我相信 Chrome 正试图使这样的代码无效。
【解决方案4】:
<script>
    window.location.hash = "no-back-button";

    // Again because Google Chrome doesn't insert
    // the first hash into the history
    window.location.hash = "Again-No-back-button"; 

    window.onhashchange = function(){
        window.location.hash = "no-back-button";
    }
</script>

【讨论】:

  • 天才!当用户在 Web 应用程序中按 Backspace(例如,在禁用/只读字段上)时,我使用它来防止意外触发 Back 按钮,而在该应用程序中,后退/前进实际上并没有任何意义。确认禁用后退和前进功能(而不是按钮本身),包括上下文菜单选项;在 IE8 到 IE11、Chrome 和 FF 中验证。
  • 这可行,但会重置在文本框中输入的所有数据。是否可以防止清除?
  • 它在 Firefox 上对我有用,但在 chrome 上却不行(版本 36.0.1985.143)
  • 这对我也有用,但在 Firefox 上它似乎破坏了 window.history.back() 功能。我们希望防止用户点击浏览器的后退按钮,但在某些情况下,我们会在页面上提供自己的后退按钮。有什么办法让它工作吗?
  • 这对我不起作用。我在 Windows 10 上使用 Chrome 版本 55。我将脚本放在多个位置(标题开头、正文结尾等),我仍然可以使用后退按钮返回上一页。
【解决方案5】:

用于限制浏览器返回事件:

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

【讨论】:

  • 这在 chrome 上效果很好!为什么人们不投票,因为这是最好的答案?
  • 我刚刚在以下浏览器上使用 Windows 10 操作系统对其进行了测试(效果很好) Chrome 版本 74.0.3729.108(官方构建)(64 位)Chrome 金丝雀版本 76.0.3780.0(官方构建)金丝雀( 32 位)Chromium 版本 66.0.3355.0(开发人员构建)(64 位)Firefox 66.0.3(64 位)EDGE IE 11 Safari 5.1.7
  • @TarıkSeyceri 因为这只适用于 a) 支持历史 API b) 页面实际上使用历史 API 来管理状态的浏览器
  • 在 Chrome 75 之后不再工作。请参阅:support.google.com/chrome/thread/8721521?hl=en
【解决方案6】:

此代码将禁用支持 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');
});

【讨论】:

  • 在任何浏览器上,在此之后尝试页面刷新/重新加载,您将陷入“找不到页面”错误,因为它试图找到一个名为 no-back-button... (浏览器也很可能在地址栏中显示no-back-button,这看起来很难看。)公平地说,这并不是唯一受此影响的解决方案。 history.pushState() 的第三个参数是 url,并且必须是当前页面的 url:请改用 location.href
  • 这对我有用。只需将“no-back-button”更改为“window.top.location.pathname + window.top.location.search”,即使在刷新时,它也会保留您所在页面的名称
  • 除其他外,这对我有用,点赞。参考stackoverflow.com/questions/19926641/…
  • 我探索过很多案例,这是一页网站的最佳解决方案
  • 这是一个非常糟糕的解决方案,因为您正在更改 URL,因此如果您回击和转发几次,chrome 将重定向到不存在的路径
【解决方案7】:

如何阻止后退功能:

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

【讨论】:

  • 虽然这可能是一个有效的答案,但您更有可能通过解释代码的作用和工作原理来帮助他人。仅代码的答案往往受到较少的积极关注,并且不如其他答案有用。
  • 在 Chrome、Firefox、IE 和 Edge 上测试。它运作良好。你救了我。
  • 在 Chrome 91 上测试过,效果很好。如果您解释@Aurora0001 提到的这里发生的事情会更好。好答案得到低票。
【解决方案8】:

Chrome 79 中没有一个对我有用的最受好评的答案。看起来 Chrome 在 75 版之后改变了其关于“后退”按钮的行为。请参见此处:

https://support.google.com/chrome/thread/8721521?hl=en

但是,在该 Google 线程中,Azrulmukmin Azmi 最后提供的答案确实有效。这是他的解决方案。

<script>
    history.pushState(null, document.title, location.href);
    history.back();
    history.forward();
    window.onpopstate = function () {
        history.go(1);
    };
</script>

Chrome 的问题是它不会触发 onpopstate 事件 除非您进行浏览器操作(即调用 history.back)。这就是为什么 我已将它们添加到脚本中。

我不完全理解他写的内容,但显然现在需要额外的 history.back() / history.forward() 来阻止 Back in Chrome 75+。

【讨论】:

  • 在搜索高和低之后,这最终也适用于 Android 浏览器,由于某种原因,我尝试过的任何其他脚本都没有检测到浏览器的后退按钮事件。谢谢,谢谢,再次感谢!在 Chrome 83 桌面和移动设备下测试并正常工作!吉恩,你是救命稻草!
  • 即使用户没有点击页面中的任何地方也可以工作。谢谢!
  • 非常感谢!这适用于任何浏览器以及移动浏览器!像魅力一样工作。继续努力吧! :)
  • 仍然可以正常工作,但是在我将浏览器升级到版本 87.0.4280.66 (Official Build) (64-bit) 后,它无法正常工作。有什么解决办法吗?
  • 由于某种原因,如果页面已加载并且没有发生导航(仍在登录页面上,Android/chrome 89 上),它对我不起作用。我所做的是重定向到登陆 URL 上的不同 URL。如果用户在第一页上单击返回,则会发生重新加载,但至少我仍在我的网站上。如果在任何导航后单击返回,则确实没有采取任何操作,没有工件。
【解决方案9】:

这是我可以做到的方式。

奇怪的是,更改 window.location 在 Google Chrome 和 Safari 中效果不佳。

location.hash 碰巧没有在 Chrome 和 Safari 的历史记录中创建条目。所以你必须使用 pushstate。

这适用于所有浏览器。

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

【讨论】:

  • IE9及以下不支持,不支持pushState。
  • 太棒了。这是一种很好的方法,适用于几乎所有最新的浏览器。
  • 在后来的 IE 中效果很好。直接在document.ready里放就好了:$(document).ready(function () { .... });
  • 请记住,您必须在“#nbb”之前添加您当前的 uri。即“帐户#nbb”
【解决方案10】:
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

此 JavaScript 代码不允许任何用户返回(适用于 Chrome、Firefox、Internet Explorer 和 Edge)。

【讨论】:

    【解决方案11】:
    <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>
    

    【讨论】:

    • event.persisted 是否有一些文档?
    • 这里是为您的问题找到的链接。找到它here@Muhd
    【解决方案12】:

    反应

    对于React项目中的modal组件,modal的openclose,控制浏览器返回是必要的动作。

    • stopBrowserBack:停止浏览器后退按钮功能,同时获得回调函数。这个回调函数是你想做的

      const stopBrowserBack = callback => {
        window.history.pushState(null, "", window.location.href);
        window.onpopstate = () => {
          window.history.pushState(null, "", window.location.href);
          callback();
        };
      };
      
    • startBrowserBack:复兴浏览器后退按钮功能:

      const startBrowserBack = () => {
        window.onpopstate = undefined;
        window.history.back();
      };
      

    你项目中的用法:

    handleOpenModal = () =>
      this.setState(
        { modalOpen: true },
        () => stopBrowserBack(this.handleCloseModal)
      );
    
    handleCloseModal = () =>
      this.setState(
        { modalOpen: false },
        startBrowserBack
      );
    

    【讨论】:

      【解决方案13】:

      This article on jordanhollinger.com 是我觉得最好的选择。类似于 Razor 的答案,但更清晰一些。代码如下;乔丹霍林格的全部功劳:

      之前的页面:

      <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'
          }
        }
      }
      

      【讨论】:

      • 当前没有任何名为“Razor”的用户。参考了哪个答案?
      【解决方案14】:

      此代码已使用最新的 Chrome 和 Firefox 浏览器进行了测试。

      <script type="text/javascript">
          history.pushState(null, null, location.href);
          history.back();
          history.forward();
          window.onpopstate = function () { history.go(1); };
      </script>
      

      【讨论】:

      • 欢迎 huyhoang。
      • 在 Chrome 85 和 Safari 14 中运行良好
      【解决方案15】:

      轻松尝试:

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

      【讨论】:

        【解决方案16】:

        非常简单干净的功能,可以在不干扰页面的情况下打破后退箭头。

        好处:

        • 即时加载并恢复原始哈希,因此用户不会因 URL 明显变化而分心。
        • 用户仍然可以通过按回 10 次退出(这是一件好事),但不会意外
        • 没有像使用onbeforeunload 的其他解决方案那样的用户干扰
        • 它只运行一次,并且不会干扰进一步的哈希操作,以防您使用它来跟踪状态
        • 恢复原始哈希,几乎不可见。
        • 使用setInterval,因此它不会破坏慢速浏览器并且始终有效。
        • 纯 JavaScript,不需要 HTML5 历史记录,适用于任何地方。
        • 不显眼、简单,并且与其他代码配合得很好。
        • 不使用unbeforeunload,它会通过模态对话框打断用户。
        • 它可以毫不费力地工作。

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

        工作原理

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

        就是这样。没有进一步的混乱,没有后台事件监控,没有别的。

        一秒用完

        要部署,只需将其添加到页面或 JavaScript 代码中的任何位置:

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

        【讨论】:

          【解决方案17】:

          在现代浏览器中这似乎可行:

          // 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)
          

          【讨论】:

            【解决方案18】:

            React(类组件)有这个问题。

            我轻松解决了:

            componentDidMount() {
                window.addEventListener("popstate", e => {
                    this.props.history.goForward();
                }
            }
            

            我从react-router-dom 使用过HashRouter

            【讨论】:

              【解决方案19】:

              你可以放一个小脚本然后检查。它不允许您访问上一页。

              这是在 JavaScript 中完成的。

              <script type="text/javascript">
                  function preventbackbutton() { window.history.forward(); }
                  setTimeout("preventbackbutton()", 0);
                  window.onunload = function () { null };
              </script>
              

              当您尝试通过浏览器访问返回或上一页时,window.onunload 函数会触发。

              【讨论】:

              • 首先是最好的工作方法。 +1
              【解决方案20】:

              这似乎对我们禁用了浏览器上的后退按钮以及退格按钮让您返回。

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

              【讨论】:

                【解决方案21】:

                立即运行代码 sn-p 并尝试返回

                history.pushState(null, null, window.location.href);
                history.back();
                window.onpopstate = () => history.forward();

                【讨论】:

                • 它在 chrome 版本 91 上不起作用
                【解决方案22】:
                <script src="~/main.js" type="text/javascript"></script>
                
                <script type="text/javascript">
                    window.history.forward();
                
                    function noBack() {
                        window.history.forward();
                    }
                </script>
                

                【讨论】:

                  【解决方案23】:

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

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

                  这适用于我的 Google Chrome 和 Firefox。

                  【讨论】:

                    【解决方案24】:

                    尝试这样做以防止 Internet Explorer 中的退格按钮默认充当“后退”:

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

                    【讨论】:

                      【解决方案25】:

                      它基本上将窗口的“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."; };
                              }
                          );

                      【讨论】:

                        【解决方案26】:

                        只需设置location.hash="Something"。按后退按钮时,哈希将从 URL 中删除,但页面不会返回。

                        这种方法可以很好地防止意外返回,但出于安全考虑,您应该设计后端以防止重新应答。

                        【讨论】:

                          【解决方案27】:

                          这里的一些解决方案不会阻止后退事件的发生 - 他们让后退事件发生(并且浏览器内存中保存的有关页面的数据丢失)然后他们播放前进事件来尝试隐藏事实刚刚发生了一个后退事件。如果页面保持瞬态,则不成功。

                          我为 React 编写了这个解决方案(当没有使用 react 路由器时),它基于 vrfvr 的回答。

                          除非用户确认弹出窗口,否则它将真正阻止后退按钮执行任何操作:

                            const onHashChange = useCallback(() => {
                              const confirm = window.confirm(
                                'Warning - going back will cause you to loose unsaved data. Really go back?',
                              );
                              window.removeEventListener('hashchange', onHashChange);
                              if (confirm) {
                                setTimeout(() => {
                                  window.history.go(-1);
                                }, 1);
                              } else {
                                window.location.hash = 'no-back';
                                setTimeout(() => {
                                  window.addEventListener('hashchange', onHashChange);
                                }, 1);
                              }
                            }, []);
                          
                            useEffect(() => {
                              window.location.hash = 'no-back';
                              setTimeout(() => {
                                window.addEventListener('hashchange', onHashChange);
                              }, 1);
                              return () => {
                                window.removeEventListener('hashchange', onHashChange);
                              };
                            }, []);
                          

                          【讨论】:

                            【解决方案28】:

                            我创建了一个 HTML 页面 (index.html)。我还在 script 文件夹/目录中创建了一个 (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>
                            

                            【讨论】:

                              【解决方案29】:

                              在我的例子中,这是一个购物订单。所以我禁用了按钮。当用户单击返回时,该按钮仍然被禁用。当他们再次单击返回时,然后单击页面按钮前进。我知道他们的订单已提交并跳到另一个页面。

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

                              【讨论】:

                                【解决方案30】:

                                此代码是完整的 javascript。 将其放在您的主页上或任何您需要的东西上,当有人返回时,它会将他们带到他们之前所在的页面。

                                <script type="text/javascript"> 
                                        function preventBack() { 
                                            window.history.forward();  
                                        } 
                                          
                                        setTimeout("preventBack()", 0); 
                                          
                                        window.onunload = function () { null }; 
                                    </script>
                                

                                【讨论】:

                                  猜你喜欢
                                  • 2014-04-17
                                  • 2017-06-29
                                  • 1970-01-01
                                  • 2023-03-08
                                  • 2023-04-03
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多