Home » Android » android – Handle URL from onCreateWindow WebView

android – Handle URL from onCreateWindow WebView

Posted by: admin June 15, 2020 Leave a comment

Questions:

Can I get URL from calling onCreateWindow on WebView?

@Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture,
        Message resultMsg) {

}
How to&Answers:

You can get clicked URL by using this code.

@Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture,
        Message resultMsg) {
    Message href = view.getHandler().obtainMessage();
    view.requestFocusNodeHref(href);

    String url = href.getData().getString("url");
    handleUrl(url); // handle the url here

    return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
}

Answer:

Try this.

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

Answer:

A version of albeee’s solution that doesn’t need to start loading the web page:

@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 boolean shouldOverrideUrlLoading (WebView view, String url) {                   handleWebViewLinks(url); // you can get your target url here
            return true; // return false if you want the load to continue
        }
    });
    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    transport.setWebView(targetWebView);
    resultMsg.sendToTarget();
    return true;
}