As you probably know from the title I work with Android WebView
. Though, I've got a specific question about @JavascriptInterface
. I'm really curious if I can make the exact method which will be working on Javascript
variables but will be called from Android
. Let's say I have an object in Javascript which got a variable named name
, then if I want to change this variable somehow I will use some kind of this function:
function () {
return this.name + ' my addition';
}
I would assign this function to another variable which will be used somewhere else. Now, I would like to do the same but in Android. Let's say I've got an object Object obj
then this object has got it's name
. My function made in @JavascriptInterface
would be like this:
@JavascriptInterface
public void changeName(Object obj){
return obj.name + " my addition";
}
If I add the JavascriptInterface
to my WebView
named "jsinterface" I would do this like this in Javascript
:
function() {
jsinterface.changeName(this.name);
}
But to be honest it doesn't work because obj.name
is null then. I know that's because I do not pass the Object
. Is there any trick to make this what I want or I really need to use webView.loadUlr("javascript: function() { ... }"};
? I would like to avoid using webView
here, that's why I ask this question.
Thanks for your time! :)
The JavaScriptInterface can only return or pass Primitive Data Types.
So it should be like this...
@JavascriptInterface
public void changeName(String obj){
........
}
Then, you need to turn a JavaScript Object to JSONObject. And turn the JSONObject to String. Then you can pass it to "changeName."
And turn the String to JSONObject in Java code.
@JavascriptInterface
public void changeName(String obj){
JSONObject js = new JSONObject(obj);
....
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.