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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36357204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:57:39  来源:igfitidea点击:

How to disable Browser back button in Angular 2

javascriptangularback-button

提问by DAN

I'm developing a web site using Angular 2. Is there any way to disable or trigger Browser back button using Angular 2?

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

Thanks

谢谢

回答by Jithin Nair

Not sure if this is already sorted, but posting the answer nonetheless, for future references. To tackle this, you basically need to add a listener in your app-component and setup a canDeactivateguard on your angular-router.

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

回答by Nishant Singh

This Very simple use the following code, This example code is from plain javascript i have converted this into angular and using in my 2-3 projects

这非常简单,使用以下代码,此示例代码来自纯 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);
        })
      }

You can define preventBackButtonin any service as well and call it from there

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

回答by Ellanki samba siva

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

its working fine to me 100% in angular2/4/5

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

回答by martin

This isn't Angular2 related problem. You can send the user back in history. See Manipulating the browser history, history.go()method particular:

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

window.history.go(-1);

However, I don't think there's a way to cancel or disable default browser action on pressing back button in the browser window because that could be very easily abused.

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

As an alternative you can show a dialog window when user tries to leave the page: javascript before leaving the page

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

回答by Shanie

A bit late perhaps but maybe somebody can use it. This is a solution I use for a page with tabs (Bootstrap 4 style) where each tab is a component.

也许有点晚,但也许有人可以使用它。这是我用于带有选项卡(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 like @Jithin Nair above but also broadcasts when an attempt to navigate was made and whether it was permitted. Subscribers of CanNavigateService can use it to decide what to do instead of back navigation.

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

Usage:

用法:

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

回答by Vijay Gawade

This issue occurs on IE browser. Use below mentioned code it will resolve your issue.

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

        }
    }

回答by Vishal Rajole

Try this

尝试这个

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

where change 'pagename' to your page name and put this into head section of page.

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

回答by Günter Z?chbauer

If you want to prevent a route to be reached you can add the @CanActivate()decorator to your routing component

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

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

See also
- Angular 2: Inject a dependency into @CanActivate?for access to global services.
- Angular2 Router - Anyone know how to use canActivate in app.ts so that I can redirect to home page if not logged in

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

回答by Charlie

Add following code in TS file of the component, where you don't want to go back.

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

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

回答by nicolapiccoli

I've tried all the solutions mentioned above but none of them worked perfectly for me. Finally I've found this npm module that worked immediately and perfectly, after two days of failed attempts.

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

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

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