Created
November 17, 2016 12:07
-
-
Save t00ts/3542ac4573ffbc73745641fa269326b8 to your computer and use it in GitHub Desktop.
Ionic 2 PWA - Controlling browser back button
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, ""); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).