Reputation: 1650
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?
Upvotes: 1
Views: 2942
Reputation: 8632
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");
Upvotes: 1
Reputation: 9982
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.
Upvotes: 0