Android webview “location.replace” doesn't wor

2019-02-11 02:51发布

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!)

3条回答
Anthone
2楼-- · 2019-02-11 03:15

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

查看更多
【Aperson】
3楼-- · 2019-02-11 03:21

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

查看更多
可以哭但决不认输i
4楼-- · 2019-02-11 03:36

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;
        }
    }
}
查看更多
登录 后发表回答