在Xamarin中从JavaScript调用c#

本文关键字:调用 JavaScript 中从 Xamarin | 更新日期: 2023-09-27 18:08:09

试着测试这个例子,但发现它不能与我一起工作,我使用API19,我的代码是:

using System;
using Android.App;
using Android.Content;  
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Webkit;
using Java.Interop;
namespace App3
{
[Activity(Label = "App3", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    int count = 1;
    const string html = @"
         <html>
         <body>
             <p>Demo calling C# from JavaScript</p>
             <button type=""button"" onClick=""CSharp.ShowToast()"">Call C#   </button>
        </body>
    </html>";
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        // Get our button from the layout resource,
        // and attach an event to it
        Button button = FindViewById<Button>(Resource.Id.MyButton);
        WebView localWebView = FindViewById<WebView>(Resource.Id.LocalWebView);
        localWebView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
        localWebView.Settings.JavaScriptEnabled = true;
        // localWebView.LoadUrl("http://developer.xamarin.com");
        // localWebView.LoadUrl("file:///android_asset/index.html");
        localWebView.LoadData(html, "text/html", null);
        button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
    }
}
    class MyJSInterface : Java.Lang.Object
    {
        Context context;
        public MyJSInterface(Context context)
        {
            this.context = context;
        }
        [Export]
        [JavascriptInterface]
        public void ShowToast()
        {
            Toast.MakeText(context, "Hello from C#", ToastLength.Short).Show();
        }
    }
}

我在这里犯了什么错误!

注意:我已经添加了一个引用monod . android .Export(所以你可以使用[Export]注释):

在Xamarin中从JavaScript调用c#

您需要在加载HTML之前将MyJavascriptInterface的实例添加到localWebView:

WebView localWebView = FindViewById<WebView>(Resource.Id.LocalWebView);
localWebView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
localWebView.Settings.JavaScriptEnabled = true;
// Add an instance of the Javascript interface named "CSharp"
localWebView.AddJavascriptInterface(new MyJSInterface(this), "CSharp");
localWebView.LoadData(html, "text/html", null);