javascript - 将多个数据传入和传出android到webview
问题描述
我对 Android 比较陌生,并且重用了 IOS 中使用的 javascript 代码。
该代码需要从 Android 传递数据。到目前为止,我看到的教程只传递了一条 toast 消息或一个简单的字符串。
我将如何从 Android 传递数据,我可以从 javascript 访问它,类似于如何data.question
或data.choices
正在被访问?
此外,下面的 javascript 在函数中将用户选择的答案返回给 Android passData()
。有人可以提供一个示例代码,我如何接受和处理返回到 Android 的值?我正在使用科特林。
<script type="text/javascript">
function printData(data) {
var questionLabel = document.getElementById("question")
questionLabel.innerHTML = data.question
var counterLabel = document.getElementById("counter")
counterLabel.innerHTML = "Question " + data.activityCounter + " of " + data.numberOfActivities
var im = document.createElement('img');
if (data.graphicURI != null) {
im.src = data.graphicURI;
im.className = 'img-fluid img-rounded image-question';
document.getElementById('imageContainer').appendChild(im)
}
var i=0, doc = document, docFrag = document.createDocumentFragment();
for (; i < data.choices.length ; i++){
var elem = doc.createElement('input');
elem.type = 'button';
elem.className = 'card mb-3 col-10 card-body';
elem.value = data.choices[i];
elem.tag = i;
elem.addEventListener("click", function() {
passData(this.value)
}, false);
docFrag.appendChild(elem);
}
document.getElementById("choicesContainer").appendChild(docFrag);
if (((window.innerHeight + window.scrollY) >= document.body.offsetHeight) == false) {
document.getElementById("seeBottom").style.display = "block";
}
}
function passData(data) {
if (confirm("Are you sure you want to submit?")) {
console.log("yes");
window.webkit.messageHandlers.answer.postMessage(data);
} else {
console.log("nO");
}
}
</script>
解决方案
首先我们需要在javascript代码和客户端android代码之间创建一个接口,
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void sendValueToAndroid(int value) {
// Do your operations on value here
// For example:
value = value * 500;
Toast.makeText(getContext(),"Value is :" + value , Toast.LENGTH_SHORT).show();
}
}
注意:不要忘记@JavascriptInterface
在函数上方添加注释,否则 JS 将无法识别该函数
然后我们可以把这个接口绑定到 webview 上,比如,
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
现在设置了android代码和javascript之间的接口。我们可以将数据从 javascript 共享到 android。
为了在javascript端访问函数,像这样调用函数,
Android.sendValueToAndroid(5);
这里Android是我们用来表示JS的标识符,这是android端的一个函数。
因此,为了拥有像这样的其他功能,请将它们添加到 WebAppInterface 类中,您可以在 JS 端访问该功能,例如
Android.yourFunction();
推荐阅读
- scala - Scala / Intellij:如果输入语句为假,则阻塞
- android - 新到达的消息未从我自己的默认 SMS 应用收件箱中检索
- tensorflow - 测试模型而不先保存它
- docker - 无法在 docker 容器中运行 FreeBSD 终端
- node.js - 在嵌入式文档节点 mongoose 中查找 id
- postgresql - 如何在 postgres 中使用 DEFAULT?
- shell - 如何在cmd中保存命令输出的单独部分
- symfony - 安装 fos/elasticabundle,需要 pagerfanta 版本
- javascript - Javascript setter - 如何在 setter 中获取 setter 的名称?
- python - 如何从训练有素的随机森林模型中获得预测?