简体   繁体   中英

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?

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;
    }
});

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 })()");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM