Android与JavaScript相互调用
Java调用JS
通过WebView
-
WebView.loadUrl()
webView.loadUrl("javascript:alert('message')");
-
WebView.evaluateJavascript()
- 直接加载js代码
webView.evaluateJavascript("" +
"var hello='hello,' ;\n" +
"var world = 'world!';\n" +
"hello.concat(world).length;\n", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
Log.e("test", "ValueCallback--->" + value);
}
});
- 加载html中的js方法
mWebView.loadUrl("javascript:callJS()");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("javascript:callJS()", null);
}
通过J2V8
- 直接执行JS脚本
public void executeIntegerScript(View view) {
V8 runtime = V8.createV8Runtime();
final int result = runtime.executeIntegerScript("" +
"var hello='hello,' ;\n" +
"var world = 'world!';\n" +
"hello.concat(world).length;\n");
System.out.println(result);
runtime.release();
}
- 通过函数名回调
/**
* 通过方法名执行JS代码
*
* @param view
*/
public void executeScriptWithMethodName(View view) {
final String fileContent = AssetsUtil.getAssetsFileContent("test.js", this);
v8.executeScript(fileContent);
final V8Array arrayArgs = new V8Array(v8).push(12).push(21);
final int result = v8.executeIntegerFunction("add", arrayArgs);
arrayArgs.release();
System.out.println("result of executeScriptWithMethodName--->" + result);
}
- 通过Function调用
/**
* 通过Function对象执行JS代码
*
* @param view
*/
public void executeScriptWithFunctionObj(View view) {
final String fileContent = AssetsUtil.getAssetsFileContent("test.js", this);
if (v8.getType("add") == V8.V8_FUNCTION) {
final V8Array args = new V8Array(v8).push(12).push(23);
final V8Function addFunction = (V8Function) v8.getObject("add");
final Object result = addFunction.call(null, args);
System.out.println("result of executeScriptWithFunctionObj--->" + result);
args.release();
addFunction.release();
}
}
JS调用Java
通过WebView
- 1.WebView.addJavascriptInterface()
html:<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Android调用 JS 代码demo</title>
<body>
<button type="button" id="button1" onclick="callAndroid()"></button>
</body>
<script>
// Android需要调用的方法
function callJS(){
alert("Android调用了JS的callJS方法");
}
function callAndroid(){
androidToJs.hello("Js调用了Java的hello方法");
}
</script>
</head>
</html>
class AndroidToJS {
@JavascriptInterface
public void hello(String msg) {
Log.e("test", "js call Java Method to say :" + msg);
}
}
webView.addJavascriptInterface(new AndroidToJS(), "androidToJs");
- 2.WebViewClient.shouldOverrideUrlLoading()-本质是url拦截
- 3.WebChromeClient.onJsAlert()、onJsConfirm()、onJsPrompt()-本质是特定方法拦截
通过J2V8
-
是什么:
- J2V8 is a set of Java bindings for Google’s popular JavaScript engine, V8. It was developed to bring highly efficient JavaScript to Android and is the workhorse behind Tabris.js. J2V8 also runs on Windows, Linux and Mac OS. In the previous tutorial we looked at how to execute JavaScript using J2V8. In this tutorial we will demonstrate how to register Java callbacks with J2V8. Java callbacks allow JavaScript to invoke Java methods. 说人话就是:J2V是Javascript-V8引擎的封装,提供给Windows,Linux,MacOS使用
-
简介
- 1.安装(Android): implementation 'com.eclipsesource.j2v8:j2v8:4.8.2@aar'
- 2.主要class
-
怎么用
The Callback:In JavaScript, functions are first-class objects, i.e. they are objects and can be manipulated and passed around just like any other object. With J2V8, any JavaScript function can be mapped to a Java method. When the function is invoked, J2V8 will call the Java method instead, passing the JS arguments to Java. 说人话:在JS中,方法也是对象,可以像其他对象一样被组装被传递,有了J2V8,任何JS方法可以被映射为Java方法。当JS方法被调用时,J2V8就会调用对应的Java 方法,并且将JS函数的参数传递给Java方法,以此完成JS方法对AndroidNative调用
-
Registering Java Methods:Java methods can be registered as JS callbacks in two different ways. You can either implement the JavaCallback interface (or JavaVoidCallback if the method doesn’t return a value) or you can register the method reflectively by specifying its signature.
说人话:这一步就是将Java方法注册,也就是完成JS方法与Java方法的一对一,或者对Java对象的多对一的绑定- Java methods can be registered as JS callbacks in two different ways. You can either implement the JavaCallback interface (or JavaVoidCallback if the method doesn’t return a value) or you can register the method reflectively by specifying its signature.
说人话:两种方式, 1。实现 JavaCallback或者JavaVoidCallBack(不需要返回值的)接口 2。指定方法的签名以反射方式注册该方法
- Java methods can be registered as JS callbacks in two different ways. You can either implement the JavaCallback interface (or JavaVoidCallback if the method doesn’t return a value) or you can register the method reflectively by specifying its signature.
JavaCallback/JavaVoidCallback
JavaVoidCallback voidCallback = new JavaVoidCallback() {
@Override
public void invoke(V8Object v8Object, V8Array parameters) {
if (parameters != null && parameters.length() != 0) {
final Object o = parameters.get(0);
System.out.println("testJ2V8WithJavaCallBack---argument-->" + o);
if (o instanceof Releasable) {
((Releasable) o).release();
}
}
}
};
//指定JS调用print方法时,回调callback中的invoke方法
v8.registerJavaMethod(voidCallback, "print");
//以下代码,控制台将打印出:testJ2V8WithJavaCallBack---argument-->hello,world,123
v8.executeScript("print('hello,world,123')");
Registering Methods Reflectively
class TestConsole {
public void log(final String message) {
System.out.println("TestConsole---[INFO] " + message);
}
public void error(final String error) {
System.out.println("TestConsole----[ERROR] " + error);
}
public void start() {
TestConsole testConsole = new TestConsole();
V8Object v8Console = new V8Object(v8);
v8.add("testConsole", v8Console);
//这里可以实现java对象与JS方法的一对一或者一对多的关系,只需Java对象中有对应的方法与之对应即可
// v8.registerJavaMethod(testConsole, "javaMethod", "jsMethod",new Class[]{String.class});
v8Console.registerJavaMethod(testConsole, "log", "log", new Class[]{String.class});
v8Console.registerJavaMethod(testConsole, "error", "error", new Class[]{String.class});
v8Console.release();
//以下代码,控制台将打印出: TestConsole---[INFO] hello,world
v8.executeScript("testConsole.log('hello,world')");
}
}