5

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()?

najm
  • 834
  • 1
  • 13
  • 32

1 Answers1

1

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! (=

Shahar.bm
  • 169
  • 8
  • That code it's working. Thanks for the help – benoffi7 Jun 19 '21 at 10:07
  • Btw shouldOverrideUrlLoading works faster than onPageStarted. – Vitalii Movchan May 12 '23 at 14:35
  • for some reason this approach fails with `W/cr_AwContents: Popup WebView bind failed: no pending content.` right after `resultMsg.sendToTarget()` and `onPageStarted`/`shouldOverrideUrlLoading` doesn't get called. Can anyone understand why? – Cool Soft May 23 '23 at 03:39