繁体   English   中英

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

[英]How to disable Browser back button in Angular 2

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

谢谢

不确定这是否已经排序,但仍然发布答案,以供将来参考。 为了解决这个问题,您基本上需要在您的应用程序组件中添加一个侦听器,并在您的 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; } }

这很简单,使用以下代码,此示例代码来自纯 javascript 我已将其转换为 angular 并在我的 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并从那里调用它

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% 工作正常

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

Github: https : //github.com/Zatikyan/angular-disable-browser-back-button#readme

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

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

另见
- Angular 2:将依赖项注入@CanActivate? 以获得全球服务。
- Angular2 路由器 - 任何人都知道如何在 app.ts 中使用 canActivate 以便我可以在未登录的情况下重定向到主页

试试这个

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

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

也许有点晚,但也许有人可以使用它。 这是我用于带有选项卡(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

尝试使用这个

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

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

        }
    }

如果您想在 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]

我使用并在所有主要浏览器上工作的代码段!

ngOnInit() {
   history.pushState(null, null, location.href);

   this.subscription = fromEvent(window, 'popstate').subscribe(_ => {
      history.pushState(null, null, location.href);
      this.openModal(`You can't make changes or go back at this time.`, 'Okay');
   });
}

ngOnDestroy() {
   this.subscription.unsubscribe();
}

为什么不只使用这个。 应该避免浏览器在历史记录中自动插入东西。 只需插入一些 main.ts (或在启动时执行的其他地方)

   history.pushState = () => {}; 
   Object.freeze(history);

这不是 Angular2 相关的问题。 您可以将用户发送回历史记录。 请参阅操纵浏览器历史记录history.go()方法特别:

window.history.go(-1);

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

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

在组件的 TS 文件中添加以下代码,您不想返回。

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

第 1 步:从 angular common 导入 Locatoion

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM