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

时间:2016-04-01 13:07:57

标签: javascript angular back-button

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

由于

14 个答案:

答案 0 :(得分:10)

不确定这是否已经排序,但仍然发布答案,以供将来参考。 要解决这个问题,您基本上需要在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;
  }
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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

window.history.go(-1);

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

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

答案 2 :(得分:1)

这非常简单,使用以下代码,该示例代码来自纯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 并从那里调用

答案 3 :(得分:1)

我已经尝试了上面提到的所有解决方案,但是它们都不适合我。终于,在经过两天的失败尝试后,我发现此npm模块可以立即且完美地工作。

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

答案 4 :(得分:1)

尝试使用这个

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

答案 5 :(得分: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

答案 6 :(得分:0)

试试这个

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

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

答案 7 :(得分: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

答案 8 :(得分:0)

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

'Like %'

答案 9 :(得分: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);
});  
}

对于我来说,在angular2 / 4/5中它可以100%正常工作

答案 10 :(得分:0)

如果您要禁用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]

答案 11 :(得分:0)

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

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

答案 12 :(得分:-1)

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

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

答案 13 :(得分:-2)

第1步:从角色commmon导入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);
  }
}