Android WebView new window null URLs on relative links

Viewed 1277

I have implemented a custom WebView with setSupportMultipleWindows() enabled. As such, I also have a custom WebChromeClient that overrides onCreateWindow()

For most uses, I was using the following snippet to retrieve the URL for a page in a new window (i.e. opened via target:_blank):

Message href = view.getHandler().obtainMessage();
view.requestFocusNodeHref(href);

String url = href.getData().getString("url");

There's null checks in place but I've removed them in the snippet above for simplicity's sake. Now the issue is that sometimes the data Bundle (returned via getData()) has a null URL for relative links (i.e. href="/somepage" instead of href="https://www.example.com/somepage/").

So I searched on SO and found another possible solution:

WebView.HitTestResult result = view.getHitTestResult();
String url = result.getExtra();

However, that also returns null. If I get the type of the data using result.getType() it returns 0, which maps to UNKNOWN_TYPE.`

I am unsure why it is returning null for the aforementioned methods. N.B. that if I disable support of multiple windows, those same links work just fine. Disabling such support, however, is not an option. Is there another way to get the URL from within onCreateWindow()?

1 Answers

I haven't verified it, but you could try the following:

 @Override
    public boolean onCreateWindow(WebView view, boolean isDialog,
            boolean isUserGesture, Message resultMsg) {
        Logger.d(Constants.TAG, "onCreateWindow"+resultMsg);
        WebView targetWebView = new WebView(getActivity()); // pass a context
        targetWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url,
                    Bitmap favicon) {
                handleWebViewLinks(url); // you can get your target url here
                super.onPageStarted(view, url, favicon);
            }
        });
        WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
        transport.setWebView(targetWebView);
        resultMsg.sendToTarget();
        return true;
    }

Hope this solves you problem! (=

Related