问题描述
我使用MonoDroid的,并想使C#code从我的WebView调用。
I'm using MonoDroid, and would like to make C# code callable from my WebView.
我这样做(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()
{
}
}
在Javascript中,cSharpObject定义,但它没有属性。
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
难道我做错了什么,或者这是否只是没有在MonoDroid的工作?
Am I doing something wrong, or does this just not work in MonoDroid?
推荐答案
A)加入[导出]属性上你的方法。
A) Add the [Export] attribute on your method.
B)在xamarian网站:
的
B) On xamarian website:http://docs.xamarin.com/android/recipes/Controls/WebView/Call_C%23_from_JavaScript
c)写一个.java文件的JavaScriptInterface类型,包括将.java
文件中有AndroidJavaSource建设行动项目,并在Activity1.OnCreate(),这样做:
C) write your JavaScriptInterface type in a .java file, include the .javafile 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");
这篇关于使用webView.AddJavascriptInterface与MonoDroid的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!