Xamarin Android two way communication between Javascript and C#

后端 未结 1 1825
暗喜
暗喜 2021-01-19 05:20

I am developing an app using Xamarin Android which has a WebView displaying a web page. I want to implement a two way communication between Javascript from WebView to c#. I

相关标签:
1条回答
  • 2021-01-19 05:59

    Yes. That is possible. If you are targeting KitKat or higher you can use:

    webView.EvaluateJavascript("enable();", null);
    

    Where in this case enable(); is a JS function.

    If you are targeting lower API levels you can use LoadUrl();:

    webView.LoadUrl("javascript:enable();");
    

    EDIT:

    The error you get where it complains on LoadUrl is because it for some reason happens on a non-UI thread.

    Since you have already passed on the Context into your JavascriptInterface class, then you can simply wrap the contents of ShowToast in:

    context.RunOnUiThread(() => {
       // stuff here
    });
    

    Just change signature from Context to Activity and it should help you marshal you back on UI thread.

    0 讨论(0)
提交回复
热议问题