Xamarin.Android 中WebView调用JS代码
学习笔记
1、新建Xamarin.Android项目,在Assets文件夹下新建test.html文件。
代码如下
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<script type="text/javascript">
function javacalljs() {
document.getElementById("content").innerHTML +=
"<br\>java调用了js函数";
}
function javacalljswithargs(arg) {
document.getElementById("content").innerHTML +=
("<br\>" + arg);
}
</script>
</head>
<body>
this is my html <br />
<a onClick="window.Test.startFunction()">点击调用java代码</a><br />
<a onClick="window.Test.startFunction('hello world')">点击调用java代码并传递参数</a>
<br />
<div id="content">内容显示</div>
</body>
</html>
2、在Activity中的OnCreate()方法设置如下
web_view = FindViewById<WebView>(Resource.Id.webView1);
web_view.Settings.JavaScriptEnabled = true;
web_view.Settings.JavaScriptCanOpenWindowsAutomatically = true;
//web_view.AddJavascriptInterface(this, "Test");//添加js接口
web_view.SetWebViewClient(new MyWebViewClient(this));
web_view.LoadUrl("file:///android_asset/map.html");
3、重写WebViewClient类,命名为MyWebViewClient,重写OnPageFinished(WebView view, string url)方法
public class MyWebViewClient : WebViewClient
public override void OnPageFinished(WebView view, string url)
{
view.EvaluateJavascript("javacalljs()", null);
base.OnPageFinished(view, url);
}
}
总结:Xamarin.Androi调用JS代码的方法有两种:
1、通过WebView的loadUrl()
2、通过WebView的evaluateJavascript()
参考博文:https://www.cnblogs.com/huguodong/archive/2016/09/05/5843182.html