[英]If else statement not working in javascript onclick() when called from android webview?
During onClick()
function which has a if else statement inside it is not working properly from android webview. 在
onClick()
函数中,其中有一个if else语句,它在android webview中无法正常工作。 I have added the code below. 我在下面添加了代码。 Kindly provide your suggestion were I am missing it.
如果我错过了,请提供您的建议。 Thanks a lot.
非常感谢。
function exampleCall(message) {
if(navigator.userAgent.match(/Android/i)) {
androidexampleCall(message);
}
if(navigator.userAgent.match(/iPhone|iPad|iPod/i)){
iOSexampleCall(message);
}
}
JS call: JS电话:
<div onclick="javascript:exampleCall('GameOn');">.... </div>
I guess the call that is not working is androidexampleCall(message)
. 我想无效的通话是
androidexampleCall(message)
。
Define a interface and add it to the webview on your activity, like: 定义一个界面并将其添加到您的活动的webview中,例如:
Webview wv;
//...
wv.addJavascriptInterface(new myJavaScriptInterface(), "CallToAnAndroidFunction");
//...
public class myJavaScriptInterface {
@JavascriptInterface
public void androidexampleCall(String message);{
//code
}
}
On your Js code you should do the call as follows: 在您的Js代码上,您应该按如下方式进行调用:
function exampleCall(message) {
if(navigator.userAgent.match(/Android/i)) {
window.CallToAnAndroidFunction.androidexampleCall(message);
}
if(navigator.userAgent.match(/iPhone|iPad|iPod/i)){
iOSexampleCall(message);
}
}
Seems like you didn't enabled Javascript for your Webview: 好像你没有为你的Webview启用Javascript:
webview.getSettings().setJavaScriptEnabled(true);
EDIT: 编辑:
Tested your code with this Webview: 使用此Webview测试您的代码:
webview = (WebView)findViewById(R.id.webView1);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://jonathanalbrieux.com/others/testagent.html");
Button buttonReload = (Button)findViewById(R.id.button1);
buttonReload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
webview.loadUrl("http://jonathanalbrieux.com/others/testagent.html");
}
});
And this page: 而这个页面:
<html>
<head>
</head>
<body>
<div id="clickable" onclick="test('a')">clickaqd</div>
<script>
function test(string){
if(navigator.userAgent.match(/Android/i)) {
var divClickable = document.getElementById("clickable");
divClickable.innerHTML = string;
}
}
</script>
</body>
And everything works correctly, maybe you have some problem in androidexampleCall
function. 一切正常,也许你在
androidexampleCall
函数中有一些问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.