Search code examples
xamarinxamarin.androidcustom-renderer

JavascriptInterface in Xamarin.Android is obsolete and cant invoke C# from Javascript


few months ago I had a custom Xamarin.Android renderer for a webview based on the sample code in https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview

Javascript code was perfectly invoking my C# code however recently after the latest updates, the WebView control is no longer able to invoke the C# action, (to be more precise, if I am targeting Android 9.0 (API level 28) or higher) using API level 27 still works fine

after more investigation, I figured out that the compiler gives a warning on [JavascriptInterface] is being obsolete! https://learn.microsoft.com/en-us/dotnet/api/android.webkit.javascriptinterface?view=xamarin-android-sdk-9 and they advised to use the (IJavascriptInterface) instead

here is the code to be reviewed

[JavascriptInterface]
[Export ("invokeAction")]
public void InvokeAction (string data)
{
    HybridWebViewRenderer hybridRenderer;
    if (hybridWebViewRenderer != null && hybridWebViewRenderer.TryGetTarget (out hybridRenderer))
    {
        hybridRenderer.Element.InvokeAction (data);
    }
}

Does anyone know how to implement this properly to fix that and get Javascript to invoke my C# code again.


Solution

  • it still works in my Xamarin.Android project with [JavascriptInterface]

    this is part of my sample :

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

    MyJSInterface 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 in html :

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

    you could refer to https://stackoverflow.com/a/54069075/10768653