Android WebView 上的 Javascript 接口的有效返回值是什么?
我有一个 Android WebView,它具有 JavaScript,它通过 addJavascriptInterface 方法调用 Android 方法:
myWebview.addJavascriptInterface(new JavascriptBridge(), "Android");
public class JavascriptBridge {
public String getAString() {
return "my_str";
}
}
这工作正常。我想向 WebView 返回一个整数列表。尝试过这个:
public class JavascriptBridge {
public int[] getMyInts() {
return new int[]{1,2,3};
}
}
但在 JS 中调用此函数返回未定义:
var myInts = Android.getMyInts();
是否有 Android Javascript 接口的有效返回类型列表?它只是原始类型吗?
I have an Android WebView that has JavaScript that is calling Android methods through the addJavascriptInterface method:
myWebview.addJavascriptInterface(new JavascriptBridge(), "Android");
public class JavascriptBridge {
public String getAString() {
return "my_str";
}
}
This works fine. I want to return a list of ints to the WebView. Tried this:
public class JavascriptBridge {
public int[] getMyInts() {
return new int[]{1,2,3};
}
}
but calling this function in JS returns undefined:
var myInts = Android.getMyInts();
Is there a list of valid return types for an Android Javascript Interface? Is it only primitives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我还没有看到有效类型的列表(用于将值传递给 Java 函数并返回),但似乎只有基元和字符串可以工作。
您可以使用 JSON(例如,在 Javascript 中进行字符串化和解析,请在 json.org 检查各种 Java 选项
I have not seen a list of valid types (for passing values to Java functions and to return), but only primitives and string seem to work.
You can use JSON (e.g. stringify and parse in Javascript, check various Java options at json.org
您可以返回任何内容、基元或对象。对象通过其 toString() 方法转换为字符串。如果 JavascriptInterface 方法返回一个 JSON 字符串(例如, toString() 输出 JSON 的对象),那么您可以直接解析该字符串:
You can return anything, primitives or Objects. Objects are converted to strings via their toString() method. If the JavascriptInterface method returns a JSON string (e.g. an Object who's toString() outputs JSON) you can then parse that string directly: