Realize clicking on the picture in the WebView and call the native control to display the picture

There are many times now that our apps have been mixed development, and the simplest and most commonly used is that some web pages use WebView for display, which requires us to understand and understand how to realize the interaction between WebView and JS. Today, let's learn how to click on a web page image in WebView and call the native control to zoom in and display.
In fact, the realization of this interaction is very simple, that is, calling native controls through JS. The basic idea is as follows:

1. First, load an html web page, either a URL or a local html file.
2. Traverse the html tag source code to find all img tag nodes.
3. Add an onClick event to the traversed img label node.
4. By clicking the added onClick event, call the native control through JS, and display the zoom.

Implementation method
We first write a simple html file with two pictures in it. The source code is very simple. code show as below:
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GBK">
    </head>
    <body>
    <h1>Show image</h1>
    <img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490585759664&di=56aa55f480140643a11c134ef8bdae07&imgtype=0&src=http%3A%2F%2Fi2.sanwen8.cn%2Fdoc%2F1610%2F704-161024211H3.jpg' style='vertical-align:middle;' />
    <h1>Second image</h1>
    <img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490585932299&di=9ab54209dc8672cdd45b817ba3b09000&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fbaike%2Fpic%2Fitem%2F5fdf8db1cb134954a4d833a0534e9258d0094a34.jpg' />
    </body>
<html>


Write this local html file and put it in the main/assets directory.

The step of setting up the WebView

is to put the html local file we wrote into the WebView. Methods as below:

mWebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = mWebView.getSettings();
        // Set permissions to interact with Js
        webSettings.setJavaScriptEnabled(true);
        // Set to allow JS popups
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //Prevent Chinese garbled characters
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        // Load JS code first
        // The format is specified as: file:///android_asset/filename.html
//        mWebView.loadUrl("file:///android_asset/image.html");
        mWebView.loadUrl("http://www.toutiao.com/a6401738581286682881/#p=1");
        //load js
        mWebView.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");

The key code is:

mWebView.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");

This line of code is the crux of the WebView's interaction with JavaScript. The above two parameters, one is the JS interface, the other is the name of the listener function.

Traverse the img node and join the monitor
mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //The function of this js function is to register the listener, traverse all img tags, and add the onClick function. The function of the function is to call the local java interface and pass the url when the image is clicked.
                mWebView.loadUrl("javascript:(function(){"
                        + "var objs = document.getElementsByTagName(\"img\"); "
                        + "for(var i=0;i<objs.length;i++)  " + "{"
                        + "    objs[i].onclick=function()  " + "    {  "
                        + "        window.imagelistner.openImage(this.src);  "
                        + "    }  " + "}" + "})()");
            }
        });
    }

Here is a line of code to pay attention to:

window.imagelistner.openImage(this.src);


Here is to add a click event to each img node. Note that this imagelistenr is actually the method name defined by mWebView.addJavascriptInterface(new JavascriptInterface(this), "imagelistner"), and openImage is the openImage method in our custom JavaScriptInterface.

Call native controls through the JS interface
// js communication interface
    public class JavascriptInterface {

        private Context context;


        public JavascriptInterface(Context context) {
            this.context = context;
        }

        @android.webkit.JavascriptInterface
        public void openImage(String img) {
            Intent intent = new Intent();
            intent.putExtra("img", img);
            intent.setClass(context, ImageActivity.class);
            context.startActivity(intent);
        }
    }

The JavascriptInterface here corresponds to new JavascriptInterface(this) in mWebView.addJavascriptInterface(new JavascriptInterface(this), "imagelistner"). In this way, we can communicate between JS and WebView through JavascriptInterface.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326240629&siteId=291194637