How to get link-URL in Android WebView with HitTestResult for a linked image (and not the image-URL) with Longclick

Sebastian picture Sebastian · Aug 28, 2012 · Viewed 12.4k times · Source

I try to catch webview longclicks to show a context menu. (see code below) When longclicking an image, I always get the image-URL as extra (for a not linked image with IMAGE_TYPE and for a linked image with SRC_IMAGE_ANCHOR_TYPE). But how can I get the Link-URL (and not the image-URL) for an image with a hyperlink?

Best, Sebastian

        mywebview.setOnLongClickListener(new OnLongClickListener() {
            public boolean onLongClick(View v) {

                final WebView webview = (WebView) v;
                final WebView.HitTestResult result = webview.getHitTestResult();

                if (result.getType() == SRC_ANCHOR_TYPE) {
                    return true;
                }

                if (result.getType() == SRC_IMAGE_ANCHOR_TYPE) {
                    return true;
                }

                if (result.getType() == IMAGE_TYPE) {
                    return true;
                }

                return false;
            }
        });

Answer

Perry_ml picture Perry_ml · Jul 26, 2013

None of solutions above worked for me on Android 4.2.2. So I looked into source code of default android web browser. I extracted solution to this exact problem - get link-URL from image link.

Source: https://github.com/android/platform_packages_apps_browser/blob/master/src/com/android/browser/Controller.java

Extracted solution:

LongClick listener:

...
mWebview.setOnLongClickListener(new OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
        HitTestResult result = mWebview.getHitTestResult();
        if (result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
            Message msg = mHandler.obtainMessage();
            mWebview.requestFocusNodeHref(msg);
        }
    }
});
...

Handler to get the URL:

private Handler mHandler = new Handler() {

    @Override
        public void handleMessage(Message msg) {
            // Get link-URL.
            String url = (String) msg.getData().get("url");

            // Do something with it.
            if (url != null) ...
        }
    };