Handling Android back button on mobile site without using Phonegap

I need to catch the Android back button event using simple Javascript (if possible),

I have a mobile site on which I want to warn the user and close the entire site when I click the "Back" button in any part of my site, I do not need to navigate my history

Note. I do not want to include Phonegap support on my site.

Any ideas would be great!

Edit: I also used

window.onbeforeunload = function() { return "Do you want to exit?"; }; 

This also does not help in my situation, because it will be called when the URL is uploaded, I move the page to the page using the div using #ID ( using Jquery Mobile <div data-role="page"></div> )

Thus, I strictly want to receive the event by pressing the Android Back button

+4
source share
3 answers

You cannot detect this event without any native Java code, so you will either have to listen to the hashchange event in conjunction with the history stack to detect when the user returns or uses Phonegap. If you need to do something before the user returns, then the only option would be some native code.

+1
source

Have you tried to catch the <body onunload=""\> event? Perhaps you could make window.close to prevent a history call.

0
source

Try window.onpopstate

 window.onpopstate = function (evt) { if (isAndroid()) { // Android hack. After printing location and state, I can read the state. Not before. var triggerCheck = "location: " + document.location + ", state: " + JSON.stringify(evt.state); //check evt.state if its previous url or not then do your thing } }; 

It is important to keep track of where you are from evt.state. This seems to work fine for me.

0
source

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


All Articles