Set in android webview back button to work properly

Question:

Hello!

I’ll say right away – I’m not a programmer, I’m a customer, so there is something I’ll say wrong – don’t throw stones, please.

I ordered a client for the site – a webview with access to only one site, in general, they made it to me, but there was one problem – by default, in the webview, the system back button closes the application, and the link on the site is in the form a href="javascript:history.go(-1) goes into a loop, that is – from page 1 the user goes to 2, and then to 3, and then presses the back button and from page 3 returns to 2, when the user presses the back button again, the user again goes to page 3 , and not to page 1, and then from 3 again to 2, from 2 again to 3, and so on forever.At the same time, if you write a link like a href="javascript:history.go(-10) – the system will take 10 steps back , and then one forward and loop again.

The solution was found like this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
    mWebView.goBack();
    return true;
}
return super.onKeyDown(keyCode, event);
}

To be honest, I don’t know what it is and where it is inserted, since I already said that I am not a programmer, but I think you will understand.

In this case, the system back button works as it should – it takes one step back, a link like a href="javascript:history.go(-X) " stops looping, but a new problem appears, a link like a href="javascript:history.go(-X) " does not take X steps back as before, but only 1, regardless of the value of X. In other webviews, I observed that it is possible to make the system button work normally, and the site is correct, but the programmer I ordered – doesn't know how to do it.

I searched and found a possible solution – use goBackOrForward() instead goBack , but the programmer I ordered the application for has no idea how this can be used, and I even more so.

In general, the task in solving which I ask for help is to implement the work of the "back" button, both system and using a script on a site like a href="javascript:history.go(-x) " in a webview on Android. It is necessary that the back button of the form history.go (-x) takes X steps back, while the system one can either take a few steps back, or one step back, or even exit the application – it doesn’t matter. The main thing is that the history.go (-x) button works and does not loop.

Help please, knowledgeable people! Forgive me if I clumsily explained anything, if anything – ask questions, I will try to answer! Thanks!

update 05/25/2014

Here, I dug out the activation code:

package mobi.infa.smolik;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity
  extends Activity
{
  ProgressBar loadingProgressBar;
  ProgressBar loadingTitle;
  WebView mWebView;

  public static boolean checkInternetConnection(Context paramContext)
  {
    ConnectivityManager localConnectivityManager = (ConnectivityManager)paramContext.getSystemService("connectivity");
    return (localConnectivityManager.getActiveNetworkInfo() != null) && (localConnectivityManager.getActiveNetworkInfo().isAvailable()) && (localConnectivityManager.getActiveNetworkInfo().isConnected());
  }

  protected void onCreate(Bundle paramBundle)
  {
    super.onCreate(paramBundle);
    requestWindowFeature(1);
    setContentView(2130903040);
    final Context localContext = getApplicationContext();
    this.loadingProgressBar = ((ProgressBar)findViewById(2131165185));
    this.mWebView = ((WebView)findViewById(2131165186));
    this.mWebView.getSettings().setJavaScriptEnabled(true);
    this.mWebView.getSettings().setUserAgentString("infa_android_v0_1");
    this.mWebView.loadUrl("http://www.site.ru");
    this.mWebView.setWebChromeClient(new WebChromeClient()
    {
      public void onGeolocationPermissionsShowPrompt(String paramAnonymousString, GeolocationPermissions.Callback paramAnonymousCallback)
      {
        paramAnonymousCallback.invoke(paramAnonymousString, true, false);
      }

      public void onProgressChanged(WebView paramAnonymousWebView, int paramAnonymousInt)
      {
        super.onProgressChanged(paramAnonymousWebView, paramAnonymousInt);
        MainActivity.this.loadingProgressBar.setProgress(paramAnonymousInt);
        if (paramAnonymousInt == 100)
        {
          MainActivity.this.loadingProgressBar.setVisibility(4);
          return;
        }
        MainActivity.this.loadingProgressBar.setVisibility(0);
      }
    });
    WebViewClient local2 = new WebViewClient()
    {
      public boolean shouldOverrideUrlLoading(WebView paramAnonymousWebView, String paramAnonymousString)
      {
        if (paramAnonymousString.contains("infa.mobi"))
        {
          if (paramAnonymousString.equalsIgnoreCase(MainActivity.this.mWebView.getUrl()))
          {
            MainActivity.this.mWebView.goBack();
            return true;
          }
          if (MainActivity.checkInternetConnection(localContext))
          {
            MainActivity.this.mWebView.loadUrl(paramAnonymousString);
            return true;
          }
          Toast localToast = Toast.makeText(localContext, "Отсутствует интернет соединение!", 1);
          localToast.setGravity(17, 0, 0);
          localToast.show();
          return true;
        }
        Intent localIntent = new Intent("android.intent.action.VIEW");
        localIntent.setData(Uri.parse(paramAnonymousString));
        MainActivity.this.startActivity(localIntent);
        return true;
      }
    };
    this.mWebView.setWebViewClient(local2);
  }

  public boolean onCreateOptionsMenu(Menu paramMenu)
  {
    paramMenu.add("На главную");
    paramMenu.add("Поделиться");
    paramMenu.add("О программе");
    paramMenu.add("Выход");
    return super.onCreateOptionsMenu(paramMenu);
  }

  public boolean onBackPressed(int paramInt, KeyEvent paramKeyEvent)
  {
    if (paramKeyEvent.getAction() == 0) {}
    switch (paramInt)
    {
    default: 
      return super.onBackPressed(paramInt, paramKeyEvent);
    }
    if (this.mWebView.canGoBack()) {
      this.mWebView.goBack();
    }
    for (;;)
    {
      return true;
      finish();
    }
  }

  public boolean onOptionsItemSelected(MenuItem paramMenuItem)
  {
    if (paramMenuItem.getTitle().toString().contains("главную")) {
      this.mWebView.loadUrl("http://www.site.ru/");
    }
    if (paramMenuItem.getTitle().toString().contains("делиться"))
    {
      Intent localIntent = new Intent("android.intent.action.SEND");
      localIntent.setType("text/plain");
      localIntent.putExtra("android.intent.extra.TEXT", "http://www.site.ru");
      localIntent.putExtra("android.intent.extra.SUBJECT", "Классный сайт!");
      startActivity(Intent.createChooser(localIntent, "Поделиться"));
    }
    if (paramMenuItem.getTitle().toString().contains("ыход")) {
      finish();
    }
    return super.onOptionsItemSelected(paramMenuItem);
  }
}

Answer:

I'm sorry, maybe I didn't fully understand the question.

public class MainActivity extends AppCompatActivity {

private WebView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.view = (WebView) findViewById(R.id.webview);
    view.loadUrl("http://www.plus2net.com/javascript_tutorial/history-object.php");
    view.getSettings().setJavaScriptEnabled(true);
}

@Override
public void onBackPressed() {
    if (view.canGoBack()) {
        view.goBack();
    } else {
        super.onBackPressed();
    }
}
}

Perfectly fulfills your requirements. By clicking on the back button, it goes all the way through the history of the webview and then closes the activity. If you click on the demo of the history object in the loaded page, you will be redirected to the page where history.go(-1) is used. By clicking on go -1 you will return back.

Scroll to Top