1

I'm using MonoDroid, and would like to make C# code callable from my WebView.

I'm doing this (C#):

protected override void OnCreate(Bundle bundle)
{
        [...]
        LinearLayout layout = FindViewById<LinearLayout>(Resource.Id.MyLayout);
        var webView = new WebView(this);
        webView.SetWebChromeClient(new WebChromeClient());
        webView.Settings.JavaScriptEnabled = true;
        webView.AddJavascriptInterface(new JSAccesibleObject(), "cSharpObject");
        webView.LoadUrl("file:///android_asset/test.html");
        layout.AddView(webView);
}

public class JSAccesibleObject : Java.Lang.Object
{
        public void method1()
        {

        }
}

In Javascript, cSharpObject is defined, but it has no properties.

alert(cSharpObject); //mynamespace.Activity1_JSAccesibleObjec@f4438fe8
for (var prop in cSharpObject) 
    alert(prop); //this never gets called
alert(cSharpObject.method1) //undefined
alert(cSharpObject.method1()) //fails

Am I doing something wrong, or does this just not work in MonoDroid?

2 Answers 2

1

A) Add the [Export] attribute on your method.

B) On xamarian website: http://docs.xamarin.com/android/recipes/Controls/WebView/Call_C%23_from_JavaScript

C) write your JavaScriptInterface type in a .java file, include the .java file in your project with a AndroidJavaSource Build action, and in Activity1.OnCreate(), do:

IntPtr JavaScriptInterface_Class = JNIEnv.FindClass ("the/package/for/JavaScriptInterface");
// TODO: Update "the/package/for" as appropriate for your type.
IntPtr JavaScriptInterface_ctor = JNIEnv.GetMethodID (JavaScriptInterface_Class, "<init>", "()V");
IntPtr instance = JNIEnv.NewObject (JavaScriptInterface_Class, JavaScriptInterface_ctor);

appView.AddJavascriptInterface (new Java.Lang.Object (instance), "Android");
Sign up to request clarification or add additional context in comments.

1 Comment

Where did you get this information on instantiating the Java object? simply doing "new JSAccesibleObject()" is actually sufficient. All he was missing was the [Export] attribute on the method...
0

You might want to look at the Java bridge code that gets generated for your JSAccesibleObject class. Look in \obj\Debug\android\src and see what kind of methods/properties are in there. These should be the methods that would be callable from Java.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.