Ionic 2 防止硬件后退按钮默认
Ionic 2 prevent hardware back button default
如何在按下硬件后退按钮时阻止默认导航?我试过 registerBackButtonAction
,但它会覆盖我不想要的每个页面中的后退按钮行为。
这也没有帮助。
document.addEventListener("backbutton", (event) => {
event.preventDefault();
}, false);
正如您在 Ionic docs registerBackButtonAction
returns 中看到的一个函数:
A function that, when called, will unregister its back button
action.
因此您可以使用该功能来恢复离开页面时的默认行为,如下所示:
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);
如何在按下硬件后退按钮时阻止默认导航?我试过 registerBackButtonAction
,但它会覆盖我不想要的每个页面中的后退按钮行为。
这也没有帮助。
document.addEventListener("backbutton", (event) => {
event.preventDefault();
}, false);
正如您在 Ionic docs registerBackButtonAction
returns 中看到的一个函数:
A function that, when called, will unregister its back button action.
因此您可以使用该功能来恢复离开页面时的默认行为,如下所示:
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);