Ionic 2防止硬件后退按钮默认

时间:2017-02-27 10:41:03

标签: angular typescript ionic-framework ionic2 ionic3

按下硬件后退按钮时,如何防止默认导航?我已经尝试了registerBackButtonAction,但随后它会覆盖我不想要的每个页面中的后退按钮的行为。

这也无济于事。

document.addEventListener("backbutton", (event) => {
      event.preventDefault();
  }, false);

1 个答案:

答案 0 :(得分:9)

正如您在Ionic docs registerBackButtonAction中看到的那样,会返回一个函数:

  

一个函数,当被调用时,将取消注册其后退按钮   动作。

因此,您可以使用该功能在离开页面时恢复默认行为,如下所示:

import { Component} from '@angular/core';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

    // Property used to store the callback of the event handler to unsubscribe to it when leaving this page
    public unregisterBackButtonAction: any;

    constructor(...) { ... }

    ionViewDidEnter() {
        this.initializeBackButtonCustomHandler();
    }

    ionViewWillLeave() {
        // Unregister the custom back button action for this page
        this.unregisterBackButtonAction && this.unregisterBackButtonAction();
    }

    public initializeBackButtonCustomHandler(): void {
        this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
            this.customHandleBackButton();
        }, 10);
    }

    private customHandleBackButton(): void {
        // do what you need to do here ...
    }
}

正如您所看到的,关键是存储registerBackButtonAction方法的回调并在以后离开页面时使用它(或者当您想要恢复默认行为时):

this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
    this.customHandleBackButton();
}, 10);