Android webview “location.replace” doesn't work

后端 未结 3 619
感情败类
感情败类 2020-12-30 18:01

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 \"

相关标签:
3条回答
  • 2020-12-30 18:18

    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

    0 讨论(0)
  • 2020-12-30 18:20

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

    0 讨论(0)
  • 2020-12-30 18:30

    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;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题