我正在尝试将 Activity 中的一些数据共享到 JavaScript,但我的所有结果都失败了,这是我当前的代码:
C#
var webView = FindViewById<WebView>(Resource.Id.webView);
webView.SetWebChromeClient(new WebChromeClient());
webView.Settings.JavaScriptCanOpenWindowsAutomatically = true;
webView.Settings.JavaScriptEnabled = true;
string script = string.Format("javascript:UpdateData('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');", "1", "2", "3", "4", "5", "6", "7", "8", "9");
webView.LoadUrl("file:///android_asset/index.html");
if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
{
webView.EvaluateJavascript(script, null);
}
else
{
webView.LoadUrl(script);
}
index.html 内的 JavaScript(我也尝试将代码添加到头部和正文的末尾):
<script type="text/javascript">
function UpdateData(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) {
alert("Hi");
}
</script>
AndroidManifest.xml
<?xml version="1.0" encoding"utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="Test.Test" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="19" />
<application android:label="Test"></application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
老实说,我不知道我做错了什么,因为什么也没有发生,基本网页呈现完美,但 JavaScript 没有被触发。有人以前经历过吗?
最佳答案
我认为问题在于您试图在加载 URL 后立即评估脚本。调用webView.LoadUrl(...)
后,WebView
需要一些时间才能完全加载页面,包括包含的 <script>
.
您需要创建一个从 WebViewClient
派生的类并覆盖 OnPageFinished
方法。
public class JavaScriptWebViewClient : WebViewClient
{
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
string script = string.Format("javascript:UpdateData('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');", "1", "2", "3", "4", "5", "6", "7", "8", "9");
if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
{
view.EvaluateJavascript(script, null);
}
else
{
view.LoadUrl(script);
}
}
}
然后您的原始代码需要设置网络客户端:
var webView = FindViewById<WebView>(Resource.Id.webView);
webView.SetWebChromeClient(new WebChromeClient());
webView.Settings.JavaScriptCanOpenWindowsAutomatically = true;
webView.Settings.JavaScriptEnabled = true;
//set the custom web client
webView.SetWebViewClient(new JavaScriptWebViewClient());
webView.LoadUrl("file:///android_asset/index.html");
关于javascript - EvaluateJavascript 或 LoadUrl 根本没有在 Xamarin 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40757527/