问题
Is there a way in Xamarin's WebView that allows me to attach javascript events to my html elements and call C# method.
I could easily do this in Android by using JavaScriptInterface
<video width="320" height="240" controls="controls" poster='poster.gif'
onclick="window.JSInterface.startVideo('file:///sdcard/test.3gp');"
How would I manage to this in Xamarin
回答1:
Create a JavaScript Interface Class
Create a C# class that contains methods to be called from JavaScript. If you are targeting Android API level 17 or later, this JavaScript-to-C# interface class must annotate each JavaScript-callable method with
[JavascriptInterface]
and[Export]
as shown in the following example. If you are targeting Android API Level 16 or earlier, this interface class must implementJava.Lang.IRunnable
as explained in Android API Level 16 and Earlier (later in this recipe):
Create a C# class that is derived from
Java.Lang.Object.
In the following example, we name our classMyJSInterface
and implement a method to display a toast when it is called fromJavaScript
:public class MyJSInterface : Java.Lang.Object { Context context; public MyJSInterface (Context context) { this.context = context; } public void ShowToast () { Toast.MakeText (context, "Hello from C#", ToastLength.Short).Show (); } }
Annotate each method that is to be exposed to JavaScript with
[Export]
and[JavascriptInterface]
(see IJavascriptInterface for more information about theJavascriptInterface
annotation). In the following example, theShowToast
method is annotated so that it can be called from JavaScript. Note that you must include theJava.Interop
andAndroid.Webkit
using statements as shown in this example:using Java.Interop; using Android.Webkit; ... [Export] [JavascriptInterface] public void ShowToast () { Toast.MakeText(context, "Hello from C#", ToastLength.Short).Show(); }
Add a project reference to Mono.Android.Export (so you can use the
[Export]
annotation):1.In Visual Studio, right-click References in the Solution Explorer and select Add Reference.... In Xamarin Studio, right-click References in the Solution Pad and select Edit References....
2.In the search field, enter
Mono.Android.Export
. When you have located it, enable the check mark next to it and click OK.
Refer :
- http://dotnetthoughts.net/how-to-invoke-c-from-javascript-in-android/
- https://developer.xamarin.com/recipes/android/controls/webview/call_csharp_from_javascript/
- https://developer.xamarin.com/samples/monodroid/WebViewJavaScriptInterface/
- https://developer.xamarin.com/api/type/Android.Webkit.JavascriptInterface/
来源:https://stackoverflow.com/questions/37930626/xamarin-webview-call-c-sharp-method