In a WebView is there a way for shouldOverrideUrlLoading to determine if it is catching a redirect vs. a user clicking a link?

前端 未结 6 585
时光说笑
时光说笑 2021-02-01 06:06

I would like to allow redirects to happen naturally in the WebView and only catch a new url if it is a happening because a user clicked something.

6条回答
  •  太阳男子
    2021-02-01 06:35

    I had a similar problem. I needed to open a page in a WebView in my activity. However, when users clicked on a link in the page, I wanted it to be opened in a "new window," meaning the browser activity. This posed a problem if the page has a redirect. In order to accomplish this, I did the following:

    1. I only show the webview once the page has finished loading.
    2. I keep a boolean telling me when the page had finished loading. User interaction can only happen after a page had finished loading. otherwise it's a redirect and should be opened in my acitivty.

    Code sample:

    private boolean mLoaded = false;
    
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(mLoaded){ // open in new browser window only if page already finished
            try
            {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                activity.startActivity(intent);
            }
            catch (Exception e)
            {
                Logger.log(e);
            }
        }
        return true;
    }
    
    @Override
    public void onPageFinished(WebView webView, String url) {
            layoutHoldingTheWebView.setVisibility(View.VISIBLE);
            mLoaded = true;
        }
    }
    

提交回复
热议问题