How to handle hardware back button in PWA developed using Ionic3 - android

I have developed a PWA (Tab based) using Ionic 3. It is working fine until hardware back button or browser's back button is pressed in android browser. If it is running from home screen, pressing hardware back will close app. If app is running in chrome in android (only tested in chrome), hardware back or browser's back will reload PWA's first page, not previously visited page. How to handle these events in Ionic 3 PWA?
I am using lazy load for all pages.
What I tried so far:
As per jgw96's comment here, I thought IonicPage will handle navigation itself. But it is not working.
Used platform.registerBackButtonAction, but it's not for PWA.
As per Webruster's suggestion below in Answers, tried code in app.component.ts. But no change.
Posting code:
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform, AlertController, Alert, Events, App, IonicApp, MenuController } from 'ionic-angular';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage:any = 'TabsPage';
constructor(public platform: Platform,
public alertCtrl: AlertController, public events: Events,
public menu: MenuController,
private _app: App,
private _ionicApp: IonicApp) {
platform.ready().then(() => {
this.configureBkBtnprocess ();
});
}
configureBkBtnprocess() {
if (window.location.protocol !== "file:") {
window.onpopstate = (evt) => {
if (this.menu.isOpen()) {
this.menu.close ();
return;
}
let activePortal = this._ionicApp._loadingPortal.getActive() ||
this._ionicApp._modalPortal.getActive() ||
this._ionicApp._toastPortal.getActive() ||
this._ionicApp._overlayPortal.getActive();
if (activePortal) {
activePortal.dismiss();
return;
}
if (this._app.getRootNav().canGoBack())
this._app.getRootNav().pop();
};
this._app.viewDidEnter.subscribe((app) => {
history.pushState (null, null, "");
});
}
}
}

you have mentioned that you are working with the hardware back button on app and in browser so you didn't mention clearly what need to be done at what stage so i came up with the generalized solution which can be useful in most of the cases
app.component.ts
platform.ready().then(() => {
// your other plugins code...
this.configureBkBtnprocess ();
});
configureBkBtnprocess
private configureBkBtnprocess () {
// If you are on chrome (browser)
if (window.location.protocol !== "file:") {
// Register browser back button action and you can perform
// your own actions like as follows
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();
}
else{
// you are in the app
};
// Fake browser history on each view enter
this._app.viewDidEnter.subscribe((app) => {
history.pushState (null, null, "");
});
Solution 2
Try to Add the these event listener in the platform ready:
window.addEventListener('load', function() { window.history.pushState({}, '')
})
window.addEventListener('popstate', function() { window.history.pushState({},
'') })

I have pretty much same requirement but none of the solution completely works, so i came up with my own. here i have used an array to keep track of visited page and removes it on back click event.
Note: window.onpopstate gets called even on pushing new page
import { Platform, Nav } from "ionic-angular";
import { HomePage } from "../pages/home/home";
#Component({
templateUrl: "app.html"
})
export class MyApp {
rootPage: any;
#ViewChild(Nav) nav: Nav;
pageHistory: string[] = [];//to track page history
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen
) {
window.addEventListener("load", function() {
//adding a state to prevent app exit on back
window.history.pushState({ noBackExitsApp: true }, "");
});
platform.ready().then(() => {
window.onpopstate = evt => {
let view = this.nav.getActive();
if (this.pageHistory.find(x => x === view.name)) {
if (!view.name.startsWith("Home")) {//handle a condition where you want to go back
this.pageHistory = this.pageHistory.filter(n => n !== view.name);
this.nav.pop().catch(reason => {
console.log("Unable to pop :" + reason);
});
}
} else {
window.history.pushState({ noBackExitsApp: true }, "");
this.pageHistory.push(view.name);
}
};
this.rootPage = HomePage;
statusBar.styleDefault();
splashScreen.hide();
});
}
}

Related

Ionic-5 app is closing instead back to previous page on click of hardware back button

I am using angular 7 and ionic 5. When i want to redirect to previous page using hardware back button, ionic app is closing itself. I am using below code but its not working.
this.platform.backButton.subscribeWithPriority(9999, () => {
document.addEventListener('backbutton', function (event) {
event.preventDefault();
event.stopPropagation();
console.log('hello');
}, false);
});
If you are using ionic with Capacitor you need to use this code in the constructor of app.component.ts:
import { App } from '#capacitor/app';
import { Location } from '#angular/common';
constructor(private _location: Location)
{
App.addListener('backButton', () =>
{
if (this._location.isCurrentPathEqualTo('/home'))
{
navigator['app'].exitApp();
}
else
{
this._location.back();
}
});
}
I use the directive for this
import { Directive, HostListener } from '#angular/core';
import { PlatformService } from 'src/app/services/platform';
#Directive({
selector: '[disableBackButton]'
})
export class DisableBackButtonDirective {
constructor(
private platformService: PlatformService
) { }
#HostListener('document:ionBackButton', ['$event'])
overrideHardwareBackAction(event: any) {
if (this.platformService.isPlatform('android')) {
event.detail.register(100, async () => {
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
});
}
}
}
in page.html
<ion-content disableBackButton>
....
</ion-content>
in page.ts
this.platform.backButton.subscribe(() => {
console.log('hello');
});
Try this,
this.platform.backButton.subscribeWithPriority(10, () => {
this.router.navigate(['']); // route to previous page or component
});

ionic 5 tabs swipe to go back not changing tabs

All the below testing and coding is done for Android phone.
I have created a new tabs project using ionic tabs. And I have 4 tabs at the bottom right now. Now the problem is I clicked on another tab no the view and then try to use the default SwipeToGoBack gesture in the phone and that does nothing.
If I go into any other page then the back gesture works fine, but when I am in the 4 pages of the tabs, it does not work.
I tried below options:
<ion-router-outlet id="main" [swipeGesture]="true"></ion-router-outlet>
IonicModule.forRoot({
swipeBackEnabled: true
}
But those did not help. I can even close the side menu bar opened by swipe back. But can not go to the previous tab by swiping back on phone. Even not able to close the app.
If the application is opened and no other tabs were clicked and I do the swipe back gesture then the app closes, but as soon as I click on other tabs then I can not even come out of the application.
I also tried adding back button listeners from the platform but that also did not help. I added below code part in the tabs.page.ts:
this.platform.backButton.subscribe(() => {
navigator.app.exitApp();
});
Any help on how to go back to the previous tab on swipe back gesture on phone and finally close the app if no previous tab history?
Links already tried:
https://github.com/ionic-team/ionic/issues/12927
Handling hardware back button in Ionic3 Vs Ionic4
Swipe through segment tabs - Ionic 3
export class TabsPage {
navigationProccess:Array<any> = [];
lastTabName:string = "";
currentBack:string = "";
constructor(private platform: Platform,private router:Router,private navctrl:NavController) {
this.router.events.subscribe((event:RouterEvent)=>{
if(event.url !== undefined){
if(this.lastTabName !== event.url && event.url !== this.currentBack){
// we put last tab name not equal event.url so the event don't go twice through array
// we put event.url not equal current back that is since when navcontroll in back button go back its considered a router event and we don't need it to be inserted again
this.pushTabHistory(event.url);
}
this.lastTabName = event.url;
}
});
this.platform.backButton.subscribeWithPriority(99999999,async()=>{
let pushHistoryCount = this.navigationProccess.length;
if(this.router.url.includes('tabs') == true && pushHistoryCount > 1){
let url = this.navigationProccess[pushHistoryCount-2].url;
this.navigationProccess.splice(pushHistoryCount-1, 1);
this.currentBack = url;
//currentBack should be assigned before navgiate back
this.navctrl.navigateBack(url);
}
})
}
pushTabHistory(tabName:string){
let navHistory = {
url:tabName
};
this.navigationProccess.push(navHistory)
}
}
Mate i've edited my answer and you where right.
Tabs don't have routeroutlet.cangoBack() since tabs and tabs/tab1ortab2ortab3 are considered one level and can't go backward.
Here i created the way to make navigation history inside array and go back and forward from this array but subscribe back is from tabs page and i make it like that since you could making it just for testing.
But As an advanced way here we go ->
1) Create A service tabnav:
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class TabnavService {
public navigationProccess:Array<any> = [];
public lastTabName:string = "";
public currentBack:string = "";
constructor() { }
pushTabHistory(tabName:string){
let navHistory = {
url:tabName
};
this.navigationProccess.push(navHistory)
}
}
2)Inside Your TabsPage:
import { TabnavService } from './../services/tabnav.service';
import { Router, RouterEvent } from '#angular/router';
import { Component } from '#angular/core';
import { NavController, Platform } from '#ionic/angular';
#Component({
selector: 'app-tabs',
templateUrl: 'tabs.page.html',
styleUrls: ['tabs.page.scss']
})
export class TabsPage {
constructor(private platform: Platform,
private router:Router,
private tabNavService:TabnavService) {
if(this.platform.is('android')){
this.router.events.subscribe((event:RouterEvent)=>{
if(event.url !== undefined){
if(this.tabNavService.lastTabName !== event.url && event.url !== this.tabNavService.currentBack){
// we put last tab name not equal event.url so the event don't go twice through array
// we put event.url not equal current back that is since when navcontroll in back button go back its considered a router event and we don't need it to be inserted again
this.tabNavService.pushTabHistory(event.url);
}
this.tabNavService.lastTabName = event.url;
}
});
}
}
}
3) In app.component.ts :
import { TabnavService } from './services/tabnav.service';
import { Component, ViewChild } from '#angular/core';
import { Platform, IonRouterOutlet, NavController } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { Router } from '#angular/router';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
#ViewChild(IonRouterOutlet,{static:false}) routerOutlet:IonRouterOutlet;
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private router:Router,
private navctrl:NavController,
private tabNavService:TabnavService
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.platform.backButton.subscribeWithPriority(99999999,async()=>{
let pushHistoryCount = this.tabNavService.navigationProccess.length;
if(this.router.url.includes('tabs') == true && pushHistoryCount > 1){
let url = this.tabNavService.navigationProccess[pushHistoryCount-2].url;
this.tabNavService.navigationProccess.splice(pushHistoryCount-1, 1);
this.tabNavService.currentBack = url;
//currentBack should be assigned before navgiate back
this.navctrl.navigateBack(url);
}else if(this.router.url.includes('tabs') == true && pushHistoryCount <2){
// here is the array less than 2 which is one (you could make it ==0 but i make it if app glitches or something)
//so if app is on main start point it exit on back pressed
navigator['app'].exitApp();
}
});
});
}
}
And Thats All ^^ . Any Help Just comment here again ^^.

Handling Ionic3 PWA back button

The issue is that when clicking the back button in the phone/desktop browser the PWA will just close as there is no handling for back button by default for ionic3 PWA. I have searched everywhere for a solution that can handle back button for ionic3 PWA but I couldn't find one that currently work.
I found a solution here:
Android Back Button on a Progressive Web Application closes de App
But I didn't know how to fix it in my app as I tried to throw it in my code when my app initialize and now its disabling the back button completely so now I am seeking for help.
My Code in app.components.ts
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.splashScreen.hide();
//Back button handling
window.addEventListener('load', function() {
window.history.pushState({}, '')
})
window.addEventListener('load', function() {
window.history.pushState({}, '')
})
window.addEventListener('popstate', function() {
window.history.pushState({}, '')
})
window.addEventListener('load', function() {
window.history.pushState({ noBackExitsApp: true }, '')
})
window.addEventListener('popstate', function(event) {
if (event.state && event.state.noBackExitsApp) {
window.history.pushState({ noBackExitsApp: true }, '')
}
})
});
}
Solution (Code in app.components.ts)
import { Platform, App, IonicApp, MenuController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
private app:App,
private ionicApp: IonicApp,
private menu: MenuController
) {
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.splashScreen.hide();
this.setupBackButtonBehavior();
});
}
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, "");
});
}
}

React Navigation + Redux close App on Back Pressed

After converting the app to redux, my react-navigation got some problem. Previously, before integrating with redux, when I press back button (Physical button) react-navigation back to the previous screen. After integrating with redux, the back button will close the app. But, it's still working with goBack() function.
I'm following the guide: https://reactnavigation.org/docs/guides/redux
And read some code from here : https://github.com/react-community/react-navigation/tree/master/examples/ReduxExample
And, this is my Navigator configuration
export const AppNavigator = StackNavigator(
{
Home: { screen: HomeScreen },
ChatDetail: { screen: ChatDetail },
PulsaDetail: { screen: PulsaDetailScreen },
Pulsa: { screen: Pulsa }
},
{
headerMode: 'none',
}
)
class AppWithNavigation extends Component {
render(){
return(
<AppNavigator navigation={ addNavigationHelpers({
dispatch: this.props.dispatch,
state: this.props.nav,
})} />
)
}
}
const mapStateToProps = (state) => ({
nav: state.nav
})
export default connect(mapStateToProps)(AppWithNavigation)
EDIT: It's can be done with manual handle & dispatch back action, but it's can't do it automaticlly? just like before using redux?
BackHandler.addEventListener('hardwareBackPress',() => {
this.props.goBack()
return true
})
After post Github issue in react-navigation repository, I got the answer.
Should add manually the back listener on top of screen / component
// App.js
import { BackAndroid } from 'react-native'
// [...]
componentDidMount() {
BackAndroid.addEventListener('backPress', () => {
const { dispatch, nav } = this.props
if (shouldCloseApp(nav)) return false
dispatch({ type: 'Back' })
return true
})
}
componentWillUnmount() {
BackAndroid.removeEventListener('backPress')
}
// [...]
https://github.com/react-community/react-navigation/issues/2117
https://github.com/react-community/react-navigation/issues/117
UPDATE:
https://facebook.github.io/react-native/docs/backhandler

Ionic - disable hardware backbutton in Windows Phone 8.1 not working

I'm developing using IONIC framework. I'm having trouble with the hardware back button.
In android the hardware back button works perfectly, but the windows phone did not work out.
When I use the back button on windows phone minimizes the application and returns the device's home.
This function only works on android:
$ionicPlatform.registerBackButtonAction(function () {
console.log("Not work in WP");
}, 100);
help !!
I found solution.
In site
https://www.hoessl.eu/2014/12/on-using-the-ionic-framework-for-windows-phone-8-1-apps/
have a post calling -> Not fixed yet: Back Button
Not fixed yet: Back Button
With Windows Phone 8.0, listening on the “backbutton” event was pretty
simple, just as with android. On WP8.1, this event is not triggered
anymore. I haven’t figured out how to enable it yet. Any hint would be
appreciated.
But a user commented the solution. follows the passage that worked in
my case
Back Button Fix :
Set your $ionicPlatform.registerBackButtonAction
$ionicPlatform.registerBackButtonAction(function (evt) {
if (evt && evt.type == ‘backclick’) {
$ionicHistory.goBack();
return true;
}
}, 100);
Hookin WinJS and send it to Ionic :
if(ionic.Platform.isWindowsPhone)
{
WinJS.Application.onbackclick = function (evt) {
$ionicPlatform.hardwareBackButtonClick(evt);
return true;
}
}
Easy Fix, long time figuring it out
Example for placing the code inside app.js
angular.module('starter', ['ionic', 'starter.menu', 'starter.services'])
.run(function ($ionicPlatform, $ionicHistory, $state, ...) {
$ionicPlatform.registerBackButtonAction(function (evt) {
if (evt && evt.type == 'backclick') {
$ionicHistory.goBack();
return true;
}
}, 100);
...
$ionicPlatform.ready(function () {
...
if (ionic.Platform.isWindowsPhone()) {
WinJS.Application.onbackclick = function (evt) {
if ($state.current.name == 'app.home') {
//function responsible for exiting the application in Windows phone 8.1
cordova.exec(null, null, "ExitApp", "execute", []);
} else {
$ionicPlatform.hardwareBackButtonClick(evt);
return true;
}
}
}
}); ...
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl',
onEnter: function ($state, UserService) {
console.log("##### - " + UserService.get().isLogged);
if (UserService.get().isLogged) {
$state.go("app.home");
}
}
})
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'MenuCtrl'
})
.state('app.secretary', {
url: '/secretary',
views: {
'menuContent': {
templateUrl: 'templates/secretary/menusecretary.html',
controller: 'MenuSecretaryCtrl'
}
}
})

Categories

Resources