JavaScript回调函数传递到Android

编程入门 行业动态 更新时间:2024-10-26 01:23:46
本文介绍了JavaScript回调函数传递到Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在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

本文发布于:2023-08-01 09:14:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267166.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   函数   JavaScript   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!