【问题标题】:Disable browser back button for one page application禁用一页应用程序的浏览器后退按钮
【发布时间】:2015-09-27 07:48:14
【问题描述】:

我需要在我的单页应用程序中禁用浏览器的后退按钮。 我尝试使用 onhashchangewindow.history.forward 之类的方法,但它们不起作用(原因可能是此处的 url 没有更改)

【问题讨论】:

    标签: javascript jquery button browser back


    【解决方案1】:

    我在 AngularJS 中工作,构建一个单页应用程序,我想禁用或阻止浏览器的后退按钮,因为我的应用程序具有用于所有导航到我的应用程序的按钮和锚点。

    我搜索并测试了很多代码,这是很容易阻止浏览器的后退按钮,下面的代码对我有用。

    window.onpopstate = 函数 (e) { window.history.forward(1); }

    当历史检测到第一个history.back()

    window.onpopstate

    被执行,然后在此之后检测到 onpopstate 事件的历史记录中的任何后退或前进。

    【讨论】:

    • 非常感谢。它运作良好。有什么方法可以禁用刷新按钮吗?
    • 这工作正常,但在另一种情况下,我通过按钮单击上一页使用 window.history.back()。它正在阻止这个也停留在同一页面上,而不是回去。我该如何解决?
    • 我使用了这种方法,但应用程序的状态发生了变化,但 url 没有改变!有什么想法吗?
    【解决方案2】:
    import { LocationStrategy } from '@angular/common';  
     constructor( private location: LocationStrategy){  
    // preventing back button in browser implemented by "Samba Siva"  
    history.pushState(null, null, window.location.href);
    this.location.onPopState(() => {  
    history.pushState(null, null, window.location.href);
    });  
    }
    

    【讨论】:

      【解决方案3】:

      我认为禁用后退按钮不会真正起作用。有很多相同的原因,但请查看this。您最好的解决方案是使用

      警告用户
      window.onbeforeunload = function() { return "You will  leave this page"; };
      

      【讨论】:

      • 试过这个。它在我的应用程序中不起作用,因为 onbeforeunload 事件不会在后退按钮上触发。
      【解决方案4】:

      从技术上讲,您无法禁用某人浏览器上的“后退”按钮,但是,您可以使该按钮不可用或继续加载同一页面。

      你可以在这里查看Disabling the Back Button

      【讨论】:

      • 我无法重新加载与会话相关的同一页面,因此包含复杂性。如何使按钮不可用?
      • 你可以使用javascript Disabled
      • 除此消息外,在此链接上没有得到任何信息:我们无法在 HTMLGoodies.com 上找到您要求的页面。
      • 只需右键单击此链接并选择在新选项卡中打开链接。只是为了给你看效果。
      【解决方案5】:

      您可以通过单击后退按钮重定向同一页面,您的页面会刷新但您每次都会在同一页面上

      【讨论】:

      • 就像我在上面的答案中所说的,我无法刷新页面。
      • 如果刷新是可以接受的,如何做到这一点?首先如何捕获返回按钮事件?
      • 更好的方法是创建一个单页应用程序并根据要求显示和隐藏相同的页面。调用 ajax 从不转发到下一页。
      【解决方案6】:

      如果用户持续点击,我认为“onpopstate”不起作用

      随便用

      window.onbeforeunload = function() { window.history.forward(1); };
      

      或者如果你想警告用户

      window.onbeforeunload = function() { return "Back button is not available!"; window.history.forward(1); };
      

      【讨论】:

        【解决方案7】:

        如果您使用的是 AngularJS,下面的代码应该可以解决问题。您必须将此代码添加到 app.js 文件或注入所有依赖项的文件中

        var myApp = angular.module('myApp', ['ngMask', 'ngRoute', 'ngAnimate', 'ngSanitize', 'ngTouch', 'ngCookies', 'ngMessages', 'ui.router', 'ui.grid', 'ui.directives', 'ui.filters', 'ui.bootstrap', 'angularUtils.directives.dirPagination']);
        myApp.run(function($rootScope, $route, $location) {
            var allowNav = false;
            var checkNav = false;
        
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toStateParams, fromState, fromStateParams) {
                allowNav = checkNav;
                checkNav = true;
            });
        
            $rootScope.$on('$locationChangeStart', function (event, next, current) {
                // Prevent the browser default action (Going back)
                if (checkNav) {
                    if (!allowNav) {
                        event.preventDefault();
                    } else {
                        allowNav = false;
                    }
                }
            });
        }); 
        

        【讨论】:

          【解决方案8】:

          我有一个不同的场景,我们想将几个页面列入黑名单。允许大部分 SPA 使用后退按钮和一些页面不允许它。我创建了一个服务来覆盖 popstate 的功能。但是,我在前进时遇到了一个奇怪的问题。

          import { RouteAddress } from 'app/common/constants/routes.constants';
          import { Injectable } from '@angular/core';
          import { StringUtilsService } from 'app/common/services/utilities/string-utils.service';
          
          @Injectable()
          export class LocationStrategyService {
              private static shouldSkip = false;
              // Array of route urls that we can't go back to.
              private static blackListed = [
                  RouteAddress.ScreeningStepTwoCreditAvailability,
                  RouteAddress.ScreeningStepTwo];
          
              constructor() {
                  window.onpopstate = this.overridingPopState;
              }
          
              overridingPopState(event: any) {
                  // This was having issue scoping
                  const isBlackListed = (navigatingTo: string): boolean => {
                      navigatingTo = navigatingTo.split('?')[0];
                      const pathFound = LocationStrategyService.blackListed.find((route) => navigatingTo.endsWith('/' + route));
                      return pathFound !== undefined && pathFound.length > 0;
                  }
          
                  // have black listed route and determing if able to go back
                  if (!LocationStrategyService.shouldSkip && isBlackListed(event.currentTarget.location.pathname)) {
                      window.history.forward();
                      // Protecting against a going forward that will redirect
                      LocationStrategyService.shouldSkip = isBlackListed(window.location.pathname);
                  } else {
                      LocationStrategyService.shouldSkip = false;
                  }
              }
          }
          

          然后在您的 AppComponent 构造函数中添加 LocationStrategyService,它会在启动时调用它。

          import { LocationStrategyService } from 'app/common/services/utilities/location-strategy.service';
          export class AppComponent {
          
          
            constructor(        
            private locationStrategyService: LocationStrategyService) {}
          }
          

          【讨论】:

            猜你喜欢
            • 2011-08-06
            • 2010-10-31
            • 2021-05-20
            • 2014-04-17
            • 1970-01-01
            • 2017-06-10
            • 2011-09-15
            相关资源
            最近更新 更多