Android WebView: definition of <a> target = "_ blank"

Is it possible to check if the user clicked the html link with the target = "_ blank".

What I want to do is display htlm in my application in WebView, but run the "external" links in the default browser for Android. The "external" link for me is related to target = "_ blank". All other links must be processed in a web view.

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 this url in android browser.

I tried it with shouldOverrideUrlLoading (), but at the moment I can’t determine if the target was "_blank" or a regular link (without a target).

I also tried setSupportMultipleWindows (true); combined with onCreateWindow (), but in this callback I cannot get the URL.

I cannot change the displayed HTML, so I cannot use the JavaScript bridge with addJavascriptInterface ()

What else can I do? Any other idea?

+5
source share
2 answers

I myself have solved this problem. 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;
    }
});
+3
source

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

inside onPageFinished (), paste a javascript code snippet into a page that does something like:

  • iterates over all elements with target = _blank attribute
  • change the href for these elements to external: // [original href]

jquery, . , , DOM Javascript.

mustOverrideUrlLoading(), ://* .

javascript, :

webView.loadUrl("javascript:(function() { PLACE YOUR JS CODE HERE })()");
+1

All Articles