Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView: Determine <a> target= "_ blank"

is it possible to check if the user has clicked on a html link with the target="_blank".

What I want to do is to display htlm in my App in a WebView, but start "external" links in the android default browser. A "external" link is for me a link with target="_blank". All other links should be handled in the webview.

So for example: the user clicks on a link like this in my WebView:

<a href="http://www.google.com" target="_blank">new window</a>

and then I want to open the given url in the android browser.

I tried it with shouldOverrideUrlLoading(), but at this point I can't determine, if the target was "_blank" or a normal link (without target).

I tried also setSupportMultipleWindows(true); in combination with onCreateWindow(), but in this callback I can't get the url.

I cant change the HTML that is displayed, so I can't use a JavaScript Bridge with addJavascriptInterface()

What else can I do? Any other idea?

like image 289
sockeqwe Avatar asked Mar 12 '13 18:03

sockeqwe


2 Answers

I just solved this issue myself. Here is how I fixed it.

mWebView.setWebChromeClient(new WebChromeListener() {
    @Override
    public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg) {
        WebView newWebView = new WebView(view.getContext());
        newWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(browserIntent);
                return true;
            }
        });
        WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
        transport.setWebView(newWebView);
        resultMsg.sendToTarget();
        return true;
    }
});
like image 184
user2966484 Avatar answered Oct 21 '22 20:10

user2966484


You can do the following: (ugly but will work)

inside onPageFinished(), inject a javascript code fragment into the page which does something like:

  1. iterates on all elements with a target=_blank attribute
  2. change the href for those elements to external://[original href]

If the site uses jquery it should be easy. If not, you can still do it using standard DOM Javascript.

on your shouldOverrideUrlLoading(), look for those external://* links and open them externally.

In order to inject the javascript , do the following:

webView.loadUrl("javascript:(function() { PLACE YOUR JS CODE HERE })()");
like image 37
yarons Avatar answered Oct 21 '22 21:10

yarons