I have a javascript interface implemented in Java that is called by my javascript code that is loaded in the webview.
JS Inside webview:
Android.myFunction(function(data){
console.log(data);
});
Java:
public class JavaScriptInterface {
Context context;
WebView webView;
JavaScriptInterface(Context c, WebView w) {
context = c;
webView = w;
}
public void myFunction(String callback) {
//when I log callback, it is "undefined"
String someData = "Yay for data";
String js =
"javascript:(function() { "
+ "var callback = " + callback + ";"
+ "callback('" + someData + "');"
+ "})()";
webView.loadUrl(js);
}
}
The string that gets loaded by webview ends up being:
javascript:(function() {var callback = undefined; undefined();})()
I have a few ideas:
a. Build the callback in JS as a string.
b. Call the callback’s toString() before passing it to Android.myFunction();
My question is, what is the best way to do this? I would love to be able to just pass objects over to Android and it magically works out. Obviously, this isn’t the case. 😉 What is the next best way to do it?
You won’t be able to pass the function in how you have it specified. You pass a function to Android.myData, but Android.myData takes a string. Instead, you probably want
You still have a problem in that you aren’t passing any data to the callback. While that’s not directly related to your question, it will become an issue since you’ll have the same cast to/from string issue (solvable via JSON… but it would be nice if Android handled that part for you).
Finally, you can probably shorten the javascript: string to
But, of course, test first 😉