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

Javascript 如何在Angular 2中禁用浏览器后退按钮,javascript,angular,back-button,Javascript,Angular,Back Button,我正在用Angular 2开发一个网站。 有没有办法使用Angular 2禁用或触发浏览器后退按钮 谢谢这不是与Angular2相关的问题。您可以将用户发送回历史记录。请参阅,history.go()methodspecial: window.history.go(-1); 但是,我不认为有办法取消或禁用浏览器窗口中按下后退按钮时的默认浏览器操作,因为这很容易被滥用 另一种方法是,当用户试图离开页面时,可以显示一个对话框窗口:如果要阻止到达路由,可以将装饰器添加到路由组件中 @Componen

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


谢谢

这不是与Angular2相关的问题。您可以将用户发送回历史记录。请参阅,
history.go()
methodspecial:

window.history.go(-1);
但是,我不认为有办法取消或禁用浏览器窗口中按下后退按钮时的默认浏览器操作,因为这很容易被滥用


另一种方法是,当用户试图离开页面时,可以显示一个对话框窗口:

如果要阻止到达路由,可以将装饰器添加到路由组件中

@Component({selector: 'control-panel-cmp', template: `<div>Settings: ...</div>`})
@CanActivate(checkIfWeHavePermission)
class ControlPanelCmp {
}
@组件({选择器:'控制面板cmp',模板:`设置:…`})
@CanActivate(检查是否拥有权限)
类控制面板{
}
另见
-访问全球服务。
-试试这个

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

pushState(null,null,'pagename');
window.addEventListener('popstate',函数(事件){
pushState(null,null,'pagename');
});

在此处,将“pagename”更改为您的页面名称,并将其放入页面的标题部分。

不确定是否已对其进行排序,但仍会发布答案,以供将来参考。 为了解决这个问题,您基本上需要在应用程序组件中添加一个侦听器,并在您的路由器上设置一个防护装置

//在app.component.ts中
从“@angular/common”导入{LocationStrategy};
@组成部分({
选择器:“应用程序根”
})
导出类AppComponent{
建造师(
私人位置:定位策略
) {
//检查是否按下后退或前进按钮。
this.location.onPopState(()=>{
//将isBackButtonClicked设置为true。
this.someNavigationService.setBackClicked(true);
返回false;
});
}
}
//导航卫士
@可注射()
导出类NavigationGuard实现CanDeactivate{
构造函数(私有someNavigationService:someNavigationService){}
canDeactivate(组件:任意){
//将阻止用户返回
if(this.someNavigationService.getBackClicked()){
this.someNavigationService.setBackClicked(false);
//再次按下当前状态以防止进一步尝试。
pushState(null,null,location.href);
返回false;
}
返回true;
}

}
步骤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);
  }
}

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

    @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

此问题发生在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;
          }

        }
    }


@HostListener('document:keydown',['$event']))
onKeyDown(evt:KeyboardEvent){
如果(
evt.keyCode==8 | | evt.which==8
) {
让doPrevent=true;
常量类型=['text'、'password'、'file'、'search'、'email'、'number'、'date'、'color'、'datetime'、'datetime-local'、'month'、'range'、'search'、'tel'、'time'、'url'、'week'];
常量目标=(evt.target);
const disabled=target.disabled | |(event.target).readOnly;
如果(!已禁用){
if(target.isContentEditable){
doPrevent=false;
}else if(target.nodeName=='INPUT'){
让type=target.type;
如果(类型){
type=type.toLowerCase();
}
if(类型索引OF(类型)>-1){
doPrevent=false;
}
}else if(target.nodeName=='TEXTAREA'){
doPrevent=false;
}
}
if(doPrevent){
evt.preventDefault();
返回false;
}
}
}

这非常简单,请使用以下代码,此示例代码来自我已将其转换为angular并在2-3项目中使用的纯javascript

// 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,并从那里调用它

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

它在angular2/4/5中100%工作正常,在组件的TS文件中添加以下代码,您不想返回

  @HostListener('window:hashchange', ['$event'])
  hashChangeHandler(e) {
    window.location.hash = "dontgoback";
  }

我已经尝试了上面提到的所有解决方案,但没有一个对我完全有效。经过两天的失败尝试,我终于找到了这个npm模块,它可以立即完美地工作


Github:

如果您希望在angular(7/8/9/10)中禁用浏览器后退按钮。。。尝试此链接并使用npm安装软件包

1) npm install --save angular-disable-browser-back-button
2) import { NgModule } from '@angular/core';
import { BackButtonDisableModule } from 'angular-disable-browser-back-button';
 
@NgModule({
  ...
  imports: [
    ...
    BackButtonDisableModule.forRoot()
  ],
  ...
})
export class AppModule {}

3)  BackButtonDisableModule.forRoot({
      preserveScrollPosition: true
    })
请使用下面给出的链接。。参考文献取自

[https://www.npmjs.com/package/angular-disable-browser-back-button][1] 试着用这个

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

我在所有主要浏览器中使用和使用的代码段

ngOnInit(){
pushState(null,null,location.href);
this.subscription:subscription=fromEvent(窗口'popstate')。subscription(=>{
pushState(null,null,location.href);
this.openModal(`此时不能进行更改或返回。`好');
});
}
恩贡德斯泰(){
this.subscription.unsubscripte();
}

window.history.back()。该服务基本上带有标志的setter和getter,它告诉您是否单击了后退按钮。您在单击后退/前进按钮时将其设置为true,然后在处理后将其重置为false。@JithinNair请同时为SomeNavigationService编写代码。这会在Safari上导致许多错误:“尝试使用history.pushState()
1) npm install --save angular-disable-browser-back-button
2) import { NgModule } from '@angular/core';
import { BackButtonDisableModule } from 'angular-disable-browser-back-button';
 
@NgModule({
  ...
  imports: [
    ...
    BackButtonDisableModule.forRoot()
  ],
  ...
})
export class AppModule {}

3)  BackButtonDisableModule.forRoot({
      preserveScrollPosition: true
    })
window.onpopstate = function (e) { window.history.forward(1); }