我想在我的 android 应用程序上运行 JavaScript 函数,这就是我创建 webview 的方式:
m_FullJSWebView = new WebView(m_VideoView.getContext());
m_FullJSWebView.loadData(htmltmp, "text/html", "UTF-8");
m_FullJSWebView.getSettings().setJavaScriptEnabled(true);
m_FullJSWebView.addJavascriptInterface(new JavaScriptInterface(m_VideoView.getContext()), "MyAndroid");
m_FullJSWebView.loadUrl("javascript:getValue()");
这是 html:
<html>
<head>
<script type="text/javascript">
function getValue(){
//return value to Android
var val= 50;
MyAndroid.receiveValueFromJs(val);
}
</script>
<title></title>
</head>
<body >
<form name="ipForm" id="ipForm">
UserName : <input type="text" name="userName">
<button type="button" onclick="getValue();">Submit</button>
</form>
</body>
</html>
这是JavascriptInterface
:
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
//add other interface methods to be called from JavaScript
public void receiveValueFromJs(String str) {
//do something useful with str
Toast.makeText(mContext, "Received Value from JS: " + str,Toast.LENGTH_SHORT).show();
}
}
在我的设备上运行它后,receiveValueFromJs
函数不会被调用。知道问题出在哪里吗?
最佳答案
来自文档:
Note that injected objects will not appear in JavaScript until the page is next (re)loaded.
这意味着您必须像这样更改您的方法顺序:
m_FullJSWebView = new WebView(m_VideoView.getContext());
m_FullJSWebView.addJavascriptInterface(new JavaScriptInterface(m_VideoView.getContext()), "MyAndroid");
m_FullJSWebView.loadData(htmltmp, "text/html", "UTF-8");
m_FullJSWebView.getSettings().setJavaScriptEnabled(true);
m_FullJSWebView.loadUrl("javascript:getValue()");
编辑(第2期)
addJavascriptInterface
中的name
参数是javascript 中java 对象的名称。它是从 javascript 调用方法的对象。
因此,您的电话应该是:
m_FullJSWebView.loadUrl("javascript:MyAndroid.getValue()");
关于java - 运行 JavaScript 方法并返回参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17672167/