Question

I've been using a bit of code (by John Evans) to execute javascript from within Dart:

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?

Was it helpful?

Solution

You will need to use postMessage to do this. For example if you have converted your variable into JSON then you can do this from inside Dart

window.postMessage(jsonMessage, "*");

and then pick it up from the JavaScript side like this

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.

OTHER TIPS

You may use dart.js to directly execute javascript functions and capture the return.

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.

You can use 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. The library takes care of converting between Dart and JavaScript objects where possible, or providing proxies if conversion isn't possible.

See also the article Using JavaScript from Dart.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top