Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect use of Android back button using JavaScript

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?

like image 929
Carasel Avatar asked Dec 04 '13 11:12

Carasel


People also ask

How can I tell if my back button is pressed in my phone?

One option is to use jquery mobile. According to this source, to detect the 'back' key, KEYCODE_BACK = 4 on Android.

What happens when we press back button in browser?

A back button in the browser lets you back-up to the copies of pages you visited previously. The web browser's back and next buttons work well with web sites that provide information that changes infrequently, such as news and shopping web sites.


2 Answers

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.

like image 176
Navjot Ahuja Avatar answered Oct 20 '22 20:10

Navjot Ahuja


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.

like image 1
Rahul Khurana Avatar answered Oct 20 '22 20:10

Rahul Khurana