我在Java中实现的JavaScript接口被称为我是在web视图加载JavaScript的code。
I have a javascript interface implemented in Java that is called by my javascript code that is loaded in the webview.
JS里面的WebView:
JS Inside webview:
Android.myFunction(function(data){ console.log(data); });
Java的:
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); } }这被通过的WebView加载的字符串结束是:
The string that gets loaded by webview ends up being:
javascript:(function() {var callback = undefined; undefined();})()
我有几个想法:
I have a few ideas:
一个。内建JS回调为字符串。
a. Build the callback in JS as a string.
乙。它传递给Android.myFunction()之前调用回调函数的toString();
b. Call the callback's toString() before passing it to Android.myFunction();
我的问题是,什么是做到这一点的最好方法是什么?我希望能够只传递对象转移到Android和它神奇的作品出来。显然,这不是这种情况。 ;)什么是做下一个最好的办法。
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?
推荐答案您将无法通过如何你有它特定的功能。你传递一个函数来Android.myData,但Android.myData需要一个字符串。相反,你可能想要
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
var myCallback = console.log; Android.myFunction("myCallback");您仍然有一个问题,你没有传递任何数据到回调。虽然这不是直接关系到你的问题,它会成为一个问题,因为你有相同的投往/返串号(通过JSON可以解决的......但是这将是很好的,如果机器人处理的那部分你)。
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).
最后,你也许可以缩短的javascript:字符串
Finally, you can probably shorten the javascript: string to
String js = "javascript:" + callback + "();";
但是,当然,测试第一;)
But, of course, test first ;)
更多推荐
JavaScript回调函数传递到Android
发布评论