[英]Ionic 2 prevent hardware back button default
How can I prevent default navigation when pressing hardware back button? 按下硬件后退按钮时如何防止默认导航? I've tried
registerBackButtonAction
, but then it overwrites behavior of back button in every page which I don't want. 我尝试过
registerBackButtonAction
,但是它覆盖了我不需要的每个页面中后退按钮的行为。
This didn't help either. 这也没有帮助。
document.addEventListener("backbutton", (event) => {
event.preventDefault();
}, false);
As you can see in Ionic docs registerBackButtonAction
returns a function: 如您在Ionic文档中所见,
registerBackButtonAction
返回一个函数:
A function that, when called, will unregister its back button action.
该函数在被调用时将取消注册其后退按钮动作。
So you can use that function to restore the default behavior when leaving the page, like this: 因此,您可以使用该函数在离开页面时恢复默认行为,如下所示:
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 ...
}
}
So as you can see, the key is to store the callback of the registerBackButtonAction
method and use it later when leaving the page (or when you want to restore the default behavior): 如您所见,关键是存储
registerBackButtonAction
方法的回调,并在以后离开页面时(或要恢复默认行为时)使用它:
this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
this.customHandleBackButton();
}, 10);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.