我创建了一个Android WebView
,并使用addJavascriptInterface(mObject,“jsinterface”)
注入了javascript
接口。它一直很正常,直到我使用new
运算符在JavaScript中创建了同名(jsinterface)的对象。
我的Java代码:
WebView mWebView = findViewById(R.id.myWebView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new MyWebChromeClient((Activity)mContext));
mWebView.addJavascriptInterface(new testClass(), "jsinterface");
mWebView.loadUrl("UrlToLoad");
testClass.java
public class testClass{
public testClass() {
}
@JavascriptInterface
public String testNativeMethod() {
return "Java method called!!";
}
}
我的JavaScript代码
test.js
function test(msg){
this.message = msg;
this.testJSMethod = function(){
return this.message;
}
}
alert(jsinterface.testNativeMethod()); // prints Java method called!!
jsinterface= new test("JS method called...");
alert(jsinterface.testJSMethod()); // prints JS method called...
alert(jsinterface.testNativeMethod()); // errors "NPMethod called on non- NPObject"
问题:
一个javascript
对象能否同时访问JavaScript方法和通过javascriptinterface
公开给它的本地JAVA
方法?有没有可能设置webview
的任何属性或执行任何JS script
来完成这个任务?