Interaction between Java and JavaScript in WebView

WebView is widely used in Android development and is often used to load web pages, such as loading news pages with WebView, opening links to this application with WebView, and displaying payment information pages with WebView. How do you interact with the content in WebView in Android development, This interaction is mainly the mutual call between Java and JavaScript. Here is how to respond to the click event of an image in WebView:

Set whether WebView supports JavaScript scripts, which is not supported by default.

public abstract void setJavaScriptEnabled(boolean flag);

Inject a Java object into WebView, and the object will be injected into the context of the JavaScript main framework. It is allowed to use the name of the mapped Java object to access the method of the object from JavaScript, and only the public method with @ javascriptinterface annotation can be accessed from JavaScript. It can be used above API level 17.

If API level 16 and earlier APIs, all public methods (including inherited) can be accessed from JavaScript. Java objects may not be injected into JavaScript before page reload, resulting in no effect of calling Java methods.

Important statement: this method allows JavaScript to control the application, which is very powerful. However, if API level 16 and earlier API versions will have certain risks. It is safer to use this method in Android 4.2 and above. If it is a lower version of JavaScript, you can use reflection to access the public fields of the injected object, Using this method in WebView may cause untrusted content to be exploited by attackers to allow applications to execute java code. Pay attention to thread safety. The fields of Java objects are inaccessible. For Android 5.0 and above, there is a certain number of methods of injected Java objects.

public void addJavascriptInterface(Object object,String name) {}

The general idea is to let the pictures in WebView respond to clicking events, and then call the Android interface to display the clicked pictures. The steps are as follows:

WebView settings support JavaScript scripts, as follows:

//设置支持JavaScript
webSettings.setJavaScriptEnabled(true);

Create classes that communicate with javascrpt and methods for JavaScript calls, as follows:

/**
 * 与 javascript 通信的 Java 对象,提供 javascript 调用方法
 * Created by jzman on 2017/7/20 0020.
 */
public class AndroidInterface {
    private Context context;
    public AndroidInterface(Context context) {
        this.context = context;
    }

    /**
     * 添加注解 @JavascriptInterface
     * javascript 要调用方法
     */
    @JavascriptInterface
    public void showImage(String imgurl){
        Intent intent = new Intent();
        intent.putExtra("img",imgurl);
        intent.setClass(context,ImageActivity.class);
        context.startActivity(intent);
    }
}

Load the content to be displayed in WebView. Here, load the HTML file in the aasets directory, as follows:

//加载 assets 目录下的 HTML 文件
webView.loadUrl("file:///android_asset/index.html");

Use the addjavascriptinterface method to map Java objects into JavaScript, as follows:

//注入Java对象并映射到JavaScript中
//参数(与javescript通信的对象,映射到JavaScript中的对象)
webView.addJavascriptInterface(new AndroidInterface(this),"imageListener");

Find the tag in JavaScript and call the method of its mapping object in its click event to open the activity displaying the picture, as follows:

<script type="text/javascript">
	function findImg(){
		//查找img标签
		var imgs = document.getElementsByTagName("img");
		//遍历img标签
		for(var i=0; i<imgs.length; i++){
			//为每一个标签设置点击事件
			imgs[i].onclick = function(){
			 //imageListener映射的Java对象
			window.imageListener.showImage(this.src);
			}
		}
	}
</script>

Call the methods in JavaScript. In order to ensure that the Java object has not been injected into JavaScript when calling, call the JavaScript methods when the page is loaded, as follows:

//设置 WebViewClient 监听相关事件
webView.setWebViewClient(new WebViewClient(){
    //页面加载完成回调该方法
    @Override
    public void onPageFinished(WebView view,String url) {
        super.onPageFinished(view,url);
        //保证页面加载完成后Java对象注入到JavaScript中
        webView.loadUrl("javascript:findImg()");
    }
});

Please refer to GitHub for the source code

We can pay attention to the official account number: jzman-blog.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>