如何运行Java脚本函数并在Android中获得回报?

时间:2019-01-07 00:59:05

标签: javascript c# android xamarin

我正在使用Xamarin C#开发一个项目,但无法运行某些Java脚本。当前是否可以调用特定的JS函数并接收其返回值?

我知道JS可以在WebView中运行;但是,如何获取输出?

此刻,JS来自我网站上的链接。任何帮助将不胜感激!


编辑

这是我尝试过的代码:

MyView.axml

 <android.webkit.WebView
            android:id="@+id/web_view"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            local:layout_constraintTop_toBottomOf="@+id/pause"
            local:layout_constraintBottom_toBottomOf="parent"/>

MyView.cs

protected override void OnCreate中叫来

webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new MyWebViewClient());
webView.LoadUrl("http://www.example.com/scheduleV5.js");

MyWebViewClient(类)

 public class MyWebViewClient : WebViewClient
{
    public override void OnPageFinished(WebView view, String url)
    {
        view.EvaluateJavascript("javascript: getSchedule();", new EvaluateBack());
    }
}

EvaluateBack(课程)

public class EvaluateBack : Java.Lang.Object, IValueCallback
{

    public void OnReceiveValue(Java.Lang.Object value)
    {
        Toast.MakeText(Android.App.Application.Context, value.ToString(), ToastLength.Short).Show();// you will get the value "100"
        var test = value.ToString();
    }
}

1 个答案:

答案 0 :(得分:3)

您可以这样做

Js调用C#中的方法

在“活动”中配置OnCreate方法:

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

创建一个C#类:

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

然后在JS中调用它:

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

您可以参考此文档:https://github.com/xamarin/recipes/tree/master/Recipes/android/controls/webview/call_csharp_from_javascript

C#在JS中调用一个方法并获取回调值

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"
        }
    }

在JS中:

<script>
      function callJS(){
        return 100;
      }
</script>