Android webview “location.replace” doesn't work

I have an Android webview with a page that redirects to another page, using location.replace(url).
Lets say that I have page "A" that redirects to page "B" (using location.replace). When pressing "back" button from page "B", the page returns to page "A", which redirects it to page "B" again. When I debug the history api (history.length), I can clearly see that on page "B" the length has incremented in "1" (only on Android 4.X webview. On iOS / web browser / Android 2.X it remains the same), which is a bug! (location.replace shouldn't change history.lenght!)

Answers:

Answer

I work with Yaniv on this project and we found the cause of the problem, it was introduced when we tried to add mailto: links handling according to this answer.

The answer suggested using the following extending class of WebViewClient:

public class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {     
        if(MailTo.isMailTo(url)){
            MailTo mt = MailTo.parse(url);
            // build intent and start new activity
            return true;
        }
        else {
            view.loadUrl(url);
            return true;
        }
    }
}

The problem was that explicitly telling the WebViewClient to load the URL and returning true (meaning "we handled this") added the page to the history. WebViews are quite capable of handling regular URLs by themselves, so returning false and not touching the view instance will let the WebView load the page and handle it as it should.

So:

public class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {     
        if(MailTo.isMailTo(url)){
            MailTo mt = MailTo.parse(url);
            // build intent and start new activity
            return true;
        }
        else {
            return false;
        }
    }
}
Answer

function locationReplace(url){
  if(history.replaceState){
    history.replaceState(null, document.title, url);
    history.go(0);
  }else{
    location.replace(url);
  }
}

Answer

Try this way..

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView mainWebView = (WebView) findViewById(R.id.webView1);

        WebSettings webSettings = mainWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        mainWebView.setWebViewClient(new MyCustomWebViewClient());
        mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        mainWebView.loadUrl("file:///android_asset/www/A.html");
    }

Or get help from this and this link

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.