I have created an android WebView
, and injected javascript
interface using addJavascriptInterface(mObject, "jsinterface")
. It works fine until I create an object with same name (jsinterface) in JavaScript using the new
operator.
WebView mWebView = findViewById(R.id.myWebView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new MyWebChromeClient((Activity)mContext));
mWebView.addJavascriptInterface(new testClass(), "jsinterface");
mWebView.loadUrl("UrlToLoad");
public class testClass{
public testClass() {
}
@JavascriptInterface
public String testNativeMethod() {
return "Java method called!!";
}
}
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"
Is this possible for a javascript
object to have access to both , i.e javascript
methods and native JAVA
methods(exposed to it via javascriptinterface
) ? Is there any possibility of setting any property to webview
OR executing any JS script
to get this done?
Think about document
in javascript. When you are in a web browser, this is a global object that you have access to at any point. If you make your own new
var called document
, you are going to have problems accessing the global document
.
When you execute this line:
mWebView.addJavascriptInterface(new testClass(), "jsinterface");
you are adding a global object called jsinterface
. This is the same situation as document
. If you create a var with the same name, it will overwrite the existing global reference.
Once you add a javascript interface to the WebView
, you don't need to create a new
reference to the interface. addJavascriptInterface
has already done that for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With