Android - Open target _blank links in WebView with external browser

Ron picture Ron · Aug 12, 2013 · Viewed 34.7k times · Source

I build a WebView which displays a website. The website contains links without a target="_blank" attribute and some with it.

I need to open the links with target defined in the external standard device browser and the ones without it inside the WebView.

I'm using a WebViewClient and I tried around with this function but still all my links are opened within the WebView:

Alternative 1:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

    return super.shouldOverrideUrlLoading(view, url);        
}

Alternative 2:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

    view.loadUrl(url);
    return true;        
}

Does anybody know how I can open blank-links externally?

Thanks!

PS: To avoid missunderstandings: I can't use this approach because the only way I know the link should be opened externallly is the target attribute.

Answer

Carson Ip picture Carson Ip · May 2, 2014

After visiting the above links, I come up with this code and hope this helps.

wv.getSettings().setSupportMultipleWindows(true);
wv.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;
    }
});