-
-
Save t00ts/3542ac4573ffbc73745641fa269326b8 to your computer and use it in GitHub Desktop.
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, ""); | |
}); | |
} | |
} | |
} |
Thanks, this script made my day as well.
Wondering why it is not the default behaviour...
Works like a charm! Thanks a lot!
Should this work on PWA with Ionic 3 lazy loading? I tried but not working.
Great work, thank you.
Since Ionic version 3.5.0, this method results in warning:
(getRootNav) is deprecated and will be removed in the next major release. Use getRootNavById instead.
So I'm suggesting this change:
var myNav = this._app.getActiveNavs()[0];
// Navigate back
if (myNav.canGoBack()) myNav.pop();
And one more thing: if browser 'back' is pressed while toast is being dismissed, it's triggering an error:
ERROR Error: Uncaught (in promise): removeView was not found
so I propose another little enhancement to catch this case, like so:
if (activePortal) {
activePortal.dismiss().catch((err)=>{console.log('gotcha (in dismiss)', err)});
return;
}
@bockoblur - your 'getrootnav' deprecation doesn't seem to work. pressing back does nothing with that code.
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).
Literally made my day finding this, thank you.