Android WebView links to same window with target=_

2020-05-21 04:27发布

I have a hybrid app that uses WebView to render external html from my own site. It had a problem that if any link was clicked, it started a browser window. I found this code to help me out and it works:

    myWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;
        }
    });

But now the problem is that I want it to not work for links that have target=_blank in them. So any normal links still open inside the WebView while the links with target=_blank should open in new browser window.

Any way we can do this?

Thanks

3条回答
2楼-- · 2020-05-21 04:36

One more setting required for webview in addition to myWebView.getSettings().setSupportMultipleWindows(true); myWebView.setJavaScriptCanOpenWindowsAutomatically(true);

查看更多
ら.Afraid
3楼-- · 2020-05-21 04:41

Try this.

myWebView.getSettings().setSupportMultipleWindows(true);
myWebView.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, android.os.Message resultMsg)
    {
        WebView.HitTestResult result = view.getHitTestResult();
        String data = result.getExtra();
        Context context = view.getContext();
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(data));
        context.startActivity(browserIntent);
        return false;
    }
});

Reference: Carson Ip

查看更多
姐就是有狂的资本
4楼-- · 2020-05-21 04:46

First,

mWebView.getSettings().setSupportMultipleWindows(true);

Then in WebChromeClient, override OnCreateWindow()

    private class MyWebChromeclient extends WebChromeClient {


    @Override
    public boolean onCreateWindow(WebView view, boolean isDialog,
            boolean isUserGesture, Message resultMsg) {

            WebView newWebView = new WebView(WebViewActivity2.this);
            view.addView(newWebView);
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(newWebView);
            resultMsg.sendToTarget();

            newWebView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW);
                    browserIntent.setData(Uri.parse(url));
                    startActivity(browserIntent);
                    return true;
                }
            });
        return true;
    }
查看更多
登录 后发表回答