ionic 2 and Angular 2 Detect Browser Back Button Functionality
Posted: November 24, 2021. | By: Admin
Add Below Code at app.component.ts
===================================
import { IonicApp, App, MenuController } from 'ionic-angular';
@Component ({...})
export class MyWebApp {
constructor (private _app: App, private _ionicApp: IonicApp, private _menu: MenuController) {
platform.ready().then(() => {
// Do your thing...
this.setupBackButtonBehavior ();
});
}
private setupBackButtonBehavior () {
// If on web version (browser)
if (window.location.protocol !== "file:") {
// Register browser back button action(s)
window.onpopstate = (evt) => {
// Close menu if open
if (this._menu.isOpen()) {
this._menu.close ();
return;
}
// Close any active modals or overlays
let activePortal = this._ionicApp._loadingPortal.getActive() ||
this._ionicApp._modalPortal.getActive() ||
this._ionicApp._toastPortal.getActive() ||
this._ionicApp._overlayPortal.getActive();
if (activePortal) {
activePortal.dismiss();
return;
}
// Navigate back
if (this._app.getRootNav().canGoBack()) this._app.getRootNav().pop();
};
// Fake browser history on each view enter
this._app.viewDidEnter.subscribe((app) => {
history.pushState (null, null, "");
});
}
}
}