'Android WebView links to same window with target=_blank to open new window

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



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

Using kotlin

myWebView.settings.javaScriptEnabled = true
myWebView.settings.javaScriptCanOpenWindowsAutomatically = true

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aashish Kumar
Solution 2 Rushabh Shah
Solution 3 Flo Cerquette