Save images from website inside a WebView?

徘徊边缘 提交于 2019-12-03 09:15:25

Right I figured it out.

Using a context menu I can hold down on an image to pull it's URL. Then I can have it initiate a download using DownloadManager. That bit is self-explanatory so I'll show the code to getting the image URL.

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    // Confirm the view is a webview
    if (v instanceof WebView) {                
        WebView.HitTestResult result = ((WebView) v).getHitTestResult();

        if (result != null) {
            int type = result.getType();

            // Confirm type is an image
            if (type == WebView.HitTestResult.IMAGE_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                String imageUrl = result.getExtra();
                Toast.makeText(this, imageUrl, Toast.LENGTH_LONG).show();

            }
        }
    }
}

I think a nice solution would be to use javascript in conjuction with WebView.addJavascriptInterface(Object,String) in order to make a"bridge" between rendered images and your Activity. A nice post about this approach is here.

Essentially you should be able to intercept an hold event over each image url via javascript, then you should send such information to your Activity via the method above in order to do whatever you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!