Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

angular - 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.

This didn't help either.

document.addEventListener("backbutton", (event) => {
      event.preventDefault();
  }, false);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you can see in Ionic docs registerBackButtonAction returns a function:

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):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...