How to run a JavaScript function and get return in Android?

前端 未结 1 1523
隐瞒了意图╮
隐瞒了意图╮ 2021-01-23 23:31

I\'m working on a project in Xamarin C# and I\'m having trouble running some Java Script. Is there currently a way to call a specific JS function and receive its return value?

相关标签:
1条回答
  • 2021-01-24 00:13

    you could do like this

    Js calls methods in C#

    Configure the OnCreate method in the Activity :

    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());
    

    Create a C# class :

    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();
        }
      }
    

    And then it's called in JS :

    <button type="button" onClick="CSharp.ShowToast ('Call C#')">Call C#</button>
    

    You can refer to this document:https://github.com/xamarin/recipes/tree/master/Recipes/android/controls/webview/call_csharp_from_javascript

    C# calls a method in JS and gets the callback value

    webView.EvaluateJavascript("javascript: callJS();", new EvaluateBack());
    
    class EvaluateBack : Java.Lang.Object,IValueCallback
        {
    
            public void OnReceiveValue(Object value)
            {
    
                Toast.MakeText(Android.App.Application.Context, value.ToString(), ToastLength.Short).Show();// you will get the value "100"
            }
        }
    

    in JS :

    <script>
          function callJS(){
            return 100;
          }
    </script>
    
    0 讨论(0)
提交回复
热议问题