Tuesday, June 19, 2018

Detect use of Android back button using JavaScript

Leave a Comment

My site has breadcrumbs which highlight which stage in a process the user has reached. The breadcrumbs rely on the browser history to tell which stage should be highlighted when the browser back button is used, but on Android devices using the hardware back button this seems to be bypassed and the highlighted breadcrumb does not change.

My site is not using PhoneGap or anything similar as it's not usually a mobile site, so is it possible to capture use of the Android back button so that I can add an event to set the breadcrumb highlight based on the history log when the button is used, just using JavaScript or jQuery?

3 Answers

Answers 1

1. Use popstate event.

https://developer.mozilla.org/en-US/docs/Web/Events/popstate

window.onpopstate = function(e) {     updateBreadCrumbObservable(); }; 

2. Use onhashchange event.

window.onhashchange = function(e) {    updateBreadCrumbObservable(); } 

You can use event argument to get more description about the event fired.

Answers 2

You can put check on inside onBackPressed method of the activity and before calling super.onBackPressed(); trigger the method to call javascript method.

for e.g:

override fun onBackPressed() {     if (handleBackPress) {         myWebView.loadUrl("javascript:backButtonPressed()")     }else {         super.onBackPressed()     } } 

in the above example if handleBackPress boolean variable is true, then it will try to call backButtonPressed() method of javascript file in the webview.

Let me know if you need any explanation or help.

Answers 3

Although mobile development is growing and refining as we speak but there are still a lot of issues which does not have any sophisticated solution to resolve them. This question is one good example of it. The first and foremost, the scope of your problem is too big for an instance, you should narrow it down. You need to specify what all browsers and platforms are you targeting. For my testing, I used IE9, IE11, Safari, Chrome and Firefox.

Working with breadcrumbs, simply means that we are monitoring user activity or his actions. Page navigation is what exactly helps us do that in this case. You would have to build a routine that is been fired at every navigation change (using window.onpopstate). You would also need to maintain a global stack that keeps the track of user activity. On every page navigation, your routine would detect whether the user moved ahead or back. This solution would be independent of any browser or platform.

Let me know if it helps!

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment