如何在Angular 2中禁用浏览器后退按钮

问题描述 投票:9回答:9

我正在使用Angular 2开发一个网站。有没有办法使用Angular 2禁用或触发浏览器后退按钮?

谢谢

javascript angular back-button
9个回答
12
投票

不确定这是否已经排序,但仍然发布答案,以供将来参考。要解决这个问题,你基本上需要在你的app-component中添加一个监听器,并在你的angular-router上设置一个canDeactivate防护。

// in app.component.ts
import { LocationStrategy } from '@angular/common';

@Component({
  selector: 'app-root'
})
export class AppComponent {
  constructor(
    private location: LocationStrategy
  ) {
    // check if back or forward button is pressed.
    this.location.onPopState(() => {
      // set isBackButtonClicked to true.
      this.someNavigationService.setBackClicked(true);
      return false;
    });
  }
}

// in navigation guard
@Injectable()
export class NavigationGuard implements CanDeactivate<any> {
  constructor(private someNavigationService: SomeNavigationService) {}
  canDeactivate(component: any) {
    // will prevent user from going back
    if (this.someNavigationService.getBackClicked()) {
      this.someNavigationService.setBackClicked(false);
      // push current state again to prevent further attempts.
      history.pushState(null, null, location.href);
      return false;
    }
    return true;
  }
}

2
投票

这非常简单使用下面的代码,这个示例代码来自普通的javascript我将它转换为角度并在我的2-3个项目中使用

// Inject LocationStrategy Service into your component
    constructor(
        private locationStrategy: LocationStrategy
      ) { }


// Define a function to handle back button and use anywhere
    preventBackButton() {
        history.pushState(null, null, location.href);
        this.locationStrategy.onPopState(() => {
          history.pushState(null, null, location.href);
        })
      }

您也可以在任何服务中定义preventBackButton并从那里调用它


1
投票

这不是Angular2相关的问题。您可以将用户重新发送回历史记录。请参阅Manipulating the browser historyhistory.go()方法特别:

window.history.go(-1);

但是,我认为有一种方法可以在浏览器窗口中按下后退按钮取消或禁用默认浏览器操作,因为这很容易被滥用。

作为替代方案,您可以在用户尝试离开页面时显示一个对话框窗口:javascript before leaving the page


0
投票

试试这个

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

将“pagename”更改为您的页面名称并将其放入页面的head部分。


0
投票

如果要阻止到达路径,可以将@CanActivate()装饰器添加到路由组件

@Component({selector: 'control-panel-cmp', template: `<div>Settings: ...</div>`})
@CanActivate(checkIfWeHavePermission)
class ControlPanelCmp {
}

也可以看看 - Angular 2: Inject a dependency into @CanActivate?获取全球服务。 - Angular2 Router - Anyone know how to use canActivate in app.ts so that I can redirect to home page if not logged in


0
投票

也许有点晚了,但也许有人可以使用它。这是我用于带有选项卡(Bootstrap 4样式)的页面的解决方案,其中每个选项卡都是一个组件。

    @Injectable()
    export class CanNavigateService {

      private static _isPermissionGranted = true
      public navigationAttempt = new Subject<boolean>()

      //-------------------------------------------------------------//

      /**Will the next navigation attempt be permitted? */
      updatePermission(isPermissionGranted: boolean) {   
        CanNavigateService._isPermissionGranted = isPermissionGranted
      }//updatePermission

      //-------------------------------------------------------------//

      /**Broadcast the last attempt and whether it was permitted */
      updateNavigationAttempt(wasPermissionGranted: boolean) {    
        this.navigationAttempt.next(wasPermissionGranted)
      }//updatePermission

      //-------------------------------------------------------------//

      /**Can we navigate? */
      public isPermissionGranted(): boolean {
        return CanNavigateService._isPermissionGranted
      }//isPermissionGranted

    }//Cls

NavigationGuard就像上面的@Jithin Nair一样,但也在尝试导航时进行广播以及是否允许进行广播。 CanNavigateService的订阅者可以使用它来决定做什么而不是后退导航。

@Injectable()
export class NavigationGuard implements CanDeactivate<any> {

constructor(private canNavigateService: CanNavigateService) { }

//--------------------------------------------------------------------//

// will prevent user from going back if permission has not been granted
canDeactivate(component: any) {

    let permitted = this.canNavigateService.isPermissionGranted()
    this.canNavigateService.updateNavigationAttempt(permitted)        

    if (!permitted) {
        // push current state again to prevent further attempts.
        history.pushState(null, null, location.href)
        return false
    }

    return true

}//canDeactivate

}//Cls

用法:

constructor(private _navigateService: CanNavigateService) {
    super()

    _navigateService.navigationAttempt.subscribe(wasPermitted => {
        //If navigation was prevented then just go to first tab
        if (!wasPermitted)
           this.onTabSelected( this._firstTab)            
    })
}//ctor

//----------------------------------------------------------------------------//

onTabSelected(tab) {

    this._selectedTab = tab
    //If it's not the first tab you can't back navigate
    this._navigateService.updatePermission(this._selectedTab == this._firstTab)
}//onTabSelected

0
投票

在IE浏览器上会出现此问题。使用下面提到的代码,它将解决您的问题。


        @HostListener('document:keydown', ['$event'])
          onKeyDown(evt: KeyboardEvent) {
            if (
                evt.keyCode === 8 || evt.which === 8
            ) {
              let doPrevent = true;
              const types =['text','password','file','search','email','number','date','color','datetime','datetime-local','month','range','search','tel','time','url','week'];
              const target = (<HTMLInputElement>evt.target);

          const disabled = target.disabled || (<HTMLInputElement>event.target).readOnly;
          if (!disabled) {
            if (target.isContentEditable) {
              doPrevent = false;
            } else if (target.nodeName === 'INPUT') {
              let type = target.type;
              if (type) {
                type = type.toLowerCase();
              }
              if (types.indexOf(type) > -1) {
                doPrevent = false;
              }
            } else if (target.nodeName === 'TEXTAREA') {
              doPrevent = false;
            }
          }


        if (doPrevent) {
            evt.preventDefault();
            return false;
          }

        }
    }


0
投票
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);
});  
}

它对我的工作很好,100%的角度2/4/5


-2
投票

第1步:从角度常见导入位置

import {Location} from "@angular/common";

第2步:在构造函数中初始化

private location: Location

第3步:在相应组件的ngOnInit中添加功能,

this.location.subscribe(currentLocation => {
if (currentLocation.url === '*/basic-info*') {
    window.onpopstate = function (event) {
        history.go(1);
    }
}

});

注意:这里/ basic-info将被您的路径替换。

如果它第一次不起作用,请尝试添加外部订阅,

let currentUrl = window.location.href;
let tmpVar = currentUrl.includes('/basic-info');
if (currentUrl.includes('/basic-info')) {
  window.onpopstate = function (event) {
    history.go(1);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.