想要在调用WebChromeClient#onCreateWindow时知道目标URL

时间:2012-08-27 12:59:24

标签: android

当我点击带有target="_blank" attributes的超链接时,会调用WebChromeClient#onCreateWindow,但我找不到新的窗口将打开的网址?主页url是我唯一能知道的东西?

我想根据目标网址更改应用行为。感谢任何帮助,谢谢!

4 个答案:

答案 0 :(得分:4)

解决

我可以通过以下方式调用点击网址

public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
    WebView.HitTestResult result = view.getHitTestResult();
    int type = result.getType();
    String data = result.getExtra();
    // do something
}

答案 1 :(得分:1)

也许我参加聚会迟到了,但上述解决方案在 Android 10 上都不适合我。所以我是这样做的:

@Override
public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, android.os.Message resultMsg) {
    WebView newWebView = new WebView(view.getContext());
    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    transport.setWebView(newWebView);
    resultMsg.sendToTarget();
    newWebView.setWebViewClient(new WebViewClient() {
        @SuppressLint("NewApi")
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return shouldOverrideUrlLoading(view, request.getUrl().toString());
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView View, String url) {
            if (url != null && !url.isEmpty()) {
               // HERE IS URL WHICH YOU WANT
            }
            return false;
        }
    });
    return true;
}

答案 2 :(得分:0)

我使用以下代码:

public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
    Message href = view.getHandler().obtainMessage();
    view.requestFocusNodeHref(href);           
    var url = href.getData()?.getString("url");

    // rest of your code
}

答案 3 :(得分:0)

以下代码段将完成工作。

@Override
    public boolean onCreateWindow (WebView view,boolean isDialog, boolean isUserGesture, Message resultMsg){
        //The default implementation
        //return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
        //This way you can get the URL
        String url = null;
        if (webView.getHitTestResult().getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE
               || webView.getHitTestResult().getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
            url = webView.getHitTestResult().getExtra();
        }
        return true;
    }

source