Xamarin.Android WebView: JavaScript callback resulting in TypeError

I’m working on a Xamarin.Android app with a WebView. I’ve set up JavaScript and the interface, but I’m running into a problem. When I try to call a C# method from JavaScript, I get this error: Uncaught TypeError: Cannot read property 'showMessage' of undefined.

Here’s what I’ve done:

  1. Enabled JavaScript and set up the interface:
webView.Settings.JavaScriptEnabled = true;
webView.AddJavascriptInterface(new JsHandler(this), "NativeApp");
  1. Created the interface:
[Export]
[JavascriptInterface]
public void DisplayText(string text)
{
    Console.WriteLine($"JS callback: {text}");
}
  1. Tried to call the C# method from JavaScript:
let selectedText = window.getSelection().toString();
NativeApp.DisplayText(selectedText);

I’ve double-checked everything, but I can’t figure out why it’s not working. Any ideas what might be causing this error? Thanks for your help!

I’ve dealt with similar WebView issues in Xamarin.Android before. One thing that’s not immediately obvious is that the JavascriptInterface needs to be on a public class. Try moving your interface to its own public class, like this:

public class JsInterface : Java.Lang.Object
{
    [JavascriptInterface]
    [Export("DisplayText")]
    public void DisplayText(string text)
    {
        // Your code here
    }
}

Then in your activity:

webView.AddJavascriptInterface(new JsInterface(), "NativeApp");

This approach has always worked for me. Also, make sure you’re not calling the JavaScript method before the page has fully loaded. You might want to wrap your JS code in a DOMContentLoaded event listener to avoid any timing issues.

Let me know if this helps.

I’ve encountered this issue in my Xamarin.Android projects. One often overlooked aspect is the threading model. Remember, WebView callbacks occur on a background thread, but UI updates must happen on the main thread. Try wrapping your C# method content in a RunOnUiThread call:

public void DisplayText(string text)
{
RunOnUiThread(() => {
// Your UI update code here
Console.WriteLine($“JS callback: {text}”);
});
}

Also, ensure your WebView is fully loaded before executing JavaScript. You might want to use webView.SetWebViewClient(new WebViewClient()) and override OnPageFinished to guarantee your JS runs at the right time. These steps have resolved similar issues for me in the past.

hey mate, i ran into this issue b4. Make sure ur using the [JavascriptInterface] attribute on the class level, not just the method. Also, double-check that ‘NativeApp’ matches exactly in both C# and JS. those fixed it for me. good luck!