Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use JavaScript/jQuery to detect the Android back button

Currently I want to make a function to detect the Android back button is pressed and do some stuff on it.

  1. The user opens the app, and clicks a button. This button lets the user to open a website.

  2. The user fills in the information on page 2, and he/she wants to go back the previous page, and he/she clicks the back button on the Android phone.

  3. The back button helps the user close the website and go back to my apps instead of back to page 1.

How can I do this with jQuery or JavaScript to check the back button pressed by user? So that I can prevent the back button close the website, but redirect to another page.

Is there a way to detect the browser Android back button event? I want to override the default setting of the Android back button, and add some code inside.

PS: Not using Java.

  • The back button on top (browser back button) can goes back to previous page.
  • The back button on the bottom (back button phone) helps me close the website.
  • I want make the bottom back button also goes back to the previous page.

See this.

like image 390
monkeyT4A Avatar asked Dec 11 '22 09:12

monkeyT4A


1 Answers

You need to override the onBackPressed on WebView Activity and check if webview can go back or not.

@Overide
public void onBackPressed() {
    if(webview.canGoBack())
        webview.goBack();
    else
        super.onBackPressed();
}

Meta: When this answer was given, the question was not specific for "JavaScript only" and "not coding in Java", etc.. i.e. handle only by the backend. This answer is strictly for the Android side, not for the backend side. I am keeping this answer if someone from Android need this answer.

like image 92
nitinkumarp Avatar answered Dec 18 '22 05:12

nitinkumarp