title: How to control the Android WebView history/back stack?
body: <p>I am trying to figure out a way to handle the WebView back stack similar to how the Android web browser handles it when the back button is pressed from within my own app's WebView.</p>
  
  <p>The problem has to do with <strong>Javascript redirects</strong>.  The WebView back stack appears to contain URLs that simply redirect.  Here is my relevant code:</p>
  
  <pre><code>private class ArticleWebViewClient extends WebViewClient {
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
          view.loadUrl(url);
          return true;
      }
  }
  
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_BACK)
      {
          WebView wv = (WebView)findViewById(R.id.web);
          if (wv.canGoBack())
          {
              wv.goBack();
  
              return true;
          }
      }
  
      return super.onKeyDown(keyCode, event);
  }
  </code></pre>
  
  <p>As you can see, pressing the back button selects the previous URL in the stack, which loads in the WebView itself after shouldOverrideUrlLoading() is called.  I'm actually doing a lot more inside shouldOverrideUrlLoading() that isn't relevant for this particular question, so "remove my WebViewClient implementation" won't work for me.  At any rate, when the previous URL is a Javascript redirect, that URL loads and then Javascript immediately redirects to the URL the WebView was just at.  I can't disable Javascript because the website depends on it.  I also can't change the website (third-party).</p>
  
  <p>The result of this redirection issue is a vicious cycle for the end-user who is frantically pressing back just to be slightly faster than the Android webpage processing engine.</p>
  
  <p>Now here is where it gets interesting:  The Android web browser handles the back button just fine for Javascript redirects!  It follows the redirects just fine but the back button does what a user expects it to do.  That means it is possible to correctly handle this scenario.  How does the Android web browser handle this problem?</p>