Using webView.AddJavascriptInterface with MonoDroid

谁都会走 提交于 2019-12-24 10:47:55

问题


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?


回答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");



回答2:


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.



来源:https://stackoverflow.com/questions/6505878/using-webview-addjavascriptinterface-with-monodroid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!