[英]How can I send and receive variables to and from javascript functions using Dart?
I've been using a bit of code (by John Evans) to execute javascript from within Dart: 我一直在使用一些代码(由John Evans提供)从Dart中执行javascript:
void injectJavascript(String javascript, [bool removeAfter = false]){
var s = new Element.tag("script");
s.attributes["type"] = "text/javascript";
s.text = javascript;
document.body.nodes.add(s);
if (removeAfter != null && removeAfter)
s.remove();
}
injectJavascript("alert('using javascript')");
But I haven't been able to send or return variables. 但我无法发送或返回变量。 Is this currently possible?
这目前可能吗? If not, any idea when it will become possible?
如果没有,任何想法何时成为可能?
You will need to use postMessage to do this. 您将需要使用postMessage来执行此操作。 For example if you have converted your variable into JSON then you can do this from inside Dart
例如,如果您已将变量转换为JSON,则可以从Dart内部执行此操作
window.postMessage(jsonMessage, "*");
window.postMessage(jsonMessage,“*”);
and then pick it up from the JavaScript side like this 然后像这样从JavaScript端拿起它
function recieveMessage(event) {
var message = JSON.parse(event.data);
:
}
window.addEventListener("message", receiveMessage, false);
If you need to work with more advanced things such as two way communication and callbacks then take a look at the code for DartGap in particular the DeviceMessageRouter class and the javascript integration layer. 如果您需要处理更高级的事情,例如双向通信和回调,那么请查看DartGap的代码,特别是DeviceMessageRouter类和javascript集成层。
You may use dart.js to directly execute javascript functions and capture the return. 您可以使用dart.js直接执行javascript函数并捕获返回值。
var result = js.context.callMethod('getAnswer', [new js.JsObject.jsify(myargs)]);
The types of passed/returned objects are however limited. 但是,传递/返回的对象的类型是有限的。 See the link above for info on which objects can be passed directly.
有关可以直接传递哪些对象的信息,请参阅上面的链接。 Note also that lists and should be 'jsified' before being used as arguments to callMethod.
还要注意列表,并且在用作callMethod的参数之前应该是'jsified'。
You can use dart:js . 你可以使用dart:js 。
This library provides access to JavaScript objects from Dart, allowing Dart code to get and set properties, and call methods of JavaScript objects and invoke JavaScript functions.
该库提供对Dart中JavaScript对象的访问,允许Dart代码获取和设置属性,调用JavaScript对象的方法并调用JavaScript函数。 The library takes care of converting between Dart and JavaScript objects where possible, or providing proxies if conversion isn't possible.
该库负责在可能的情况下在Dart和JavaScript对象之间进行转换,或者在无法进行转换时提供代理。
See also the article Using JavaScript from Dart . 另请参阅使用Dart中的JavaScript文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.