Skip to content

Instantly share code, notes, and snippets.

@t00ts
Created November 17, 2016 12:07
Show Gist options
  • Save t00ts/3542ac4573ffbc73745641fa269326b8 to your computer and use it in GitHub Desktop.
Save t00ts/3542ac4573ffbc73745641fa269326b8 to your computer and use it in GitHub Desktop.
Ionic 2 PWA - Controlling browser back button
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, "");
});
}
}
}
@janiylikorpi
Copy link

janiylikorpi commented Mar 14, 2019

This is great, but it's not working well (Ionic 3). If I hit browser back button more that once, it will navigate back and in my case results in error as navigation stack is empty (no root).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment