Close the cordova application on the back button

I have the following logic for my mobile app using cordova and angular.js

Handle my logic in mobile.js included in index.html like saving files on an SD card and then redirecting the user to a second html page using

window.location.href="main.html"; 

which will use files placed in sdcard using mobile.js

The problem I am facing is that when I am on the main.html main page and the user clicks the back button, it returns to the index.html file and then after processing returns to main.html instead of Closing the application .

I tried using the history.length object using the "backbutton" eventListener

  document.addEventListener('deviceready',function(){ document.addEventListener('backbutton',function(e){ console.log("history is "+history.length); if(history.length==1){ e.preventDefault(); navigator.app.exitApp(); } else{ navigator.app.backHistory(); } },false); },false); 

but it does not reduce the length when returning, it only increases it, so the application returns to index.html. (history.length is always greater than 1)

I found an affordable solution, for example

 document.addEventListener("backbutton", function(e){ if($.mobile.activePage.is('#homepage')){ /* Event preventDefault/stopPropagation not required as adding backbutton listener itself override the default behaviour. Refer below PhoneGap link. */ //e.preventDefault(); navigator.app.exitApp(); } else { navigator.app.backHistory() } }, false); 

but the problem with using it is that the user goes to

 second-page->homepage->third-page->homepage 

the application will exit, but instead go to the third page.

+5
source share
1 answer

You can use the jQuery mobile pageload event to save your own history list, the length of which decreases when you return. Something like this (untested from the head, so it might not be entirely correct):

 var pageHistory = []; $(document).on("deviceready", onDeviceReady); function onDeviceReady(){ $(document).on("pagecontainerload", onPageLoad); $(document).on("backbutton", onBackButton); } function onBackButton(e){ e.preventDefault(); pageHistory.pop(); if(pageHistory.length==0){ navigator.app.exitApp(); } else{ navigator.app.backHistory(); } } function onPageLoad(e, ui){ var pageId = ui.toPage.attr('id'); if(pageId !== pageHistory[pageHistory.length]){ pageHistory.push(pageId); } } 
+1
source

Source: https://habr.com/ru/post/1214326/


All Articles