几个月前,我根据中的示例代码为 Web View 创建了一个自定义 Xamarin.Android 渲染器 https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview
Javascript 代码完美地调用了我的 C# 代码,但是最近在最新更新之后,WebView 控件不再能够调用 C# 操作, (更准确地说,如果我的目标是 Android 9.0(API 级别 28)或更高版本) 使用 API 级别 27 仍然可以正常工作
经过更多调查,我发现编译器在 [JavascriptInterface] is being obsolete 上发出了警告! https://learn.microsoft.com/en-us/dotnet/api/android.webkit.javascriptinterface?view=xamarin-android-sdk-9 他们建议改用 (IJavascriptInterface)
这里是待审核的代码
[JavascriptInterface]
[Export ("invokeAction")]
public void InvokeAction (string data)
{
HybridWebViewRenderer hybridRenderer;
if (hybridWebViewRenderer != null && hybridWebViewRenderer.TryGetTarget (out hybridRenderer))
{
hybridRenderer.Element.InvokeAction (data);
}
}
有谁知道如何正确地实现它来修复它并让 Javascript 再次调用我的 C# 代码。
最佳答案
它仍然可以在我的 Xamarin.Android 项目中使用 [JavascriptInterface]
这是我的样本的一部分:
var webview = FindViewById<WebView>(Resource.Id.webView1);
WebSettings settings = webview.Settings;
settings.JavaScriptEnabled = true;
// load the javascript interface method to call the foreground method
webView.AddJavascriptInterface(new MyJSInterface(this), "CSharp");
webview.SetWebViewClient(new WebViewClient());
MyJSInterface 类:
class MyJSInterface : Java.Lang.Object
{
Context context;
public MyJSInterface (Context context)
{
this.context = context;
}
[JavascriptInterface]
[Export]
public void ShowToast (string msg)
{
Toast.MakeText(context, msg, ToastLength.Short).Show();
}
}
在 html 中:
<button type="button" onClick="CSharp.ShowToast ('Call C#')">Call C#</button>
关于xamarin - Xamarin.Android 中的 JavascriptInterface 已过时,无法从 Javascript 调用 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58739703/