Call JavaScript from Dart - First Look

UPDATE: This article is deprecated. Dart has an improved Dart-JavaScript interop library, now included in the Dart SDK. Please read about dart:js and how to use it.

If possible, do not use the js package that this blog post talks about. The js package will bloat your code.


---



You can use Dart to access existing JavaScript code, thanks to the Dart-JS Interop package. Call JavaScript functions from Dart, send Dart callbacks to JavaScript, and more!



The Dart core libraries have a lot of functionality provided out of the box (collections, querying the DOM, dates and times, math, and more), so you can get quite far with just the Dart SDK and the many pub packages. However, there are plenty of useful JavaScript libraries that can really help enhance Dart web apps. Luckily, Dart can synchronously talk to JavaScript!

Step 1: Install the js package

Add the following to your pubspec.yaml file:

dependencies:
  js: any

Step 2: Get a JavaScript library

Hugs make you feel better, let's use the hugs.js library:

function Hug(strength) {
  this.strength = strength;
}

Hug.prototype.embrace = function(length) {
  return 'Thanks, that was a good hug for ' + length + ' minutes!';
}

Hug.prototype.patBack = function(onDone) {
  onDone('All done.');
}

Be sure to include the JavaScript files in your main HTML file:

<script src="hugs.js"></script>
<script src="packages/browser/dart.js"></script>
<script src="packages/browser/interop.js"></script>

Step 3: Write Dart code

import 'dart:html';
import 'package:js/js.dart' as js;

void main() {
  // Grab the context from JS land.
  var context = js.context;
  
  // Use the [] notation to let --minify work.
  // See https://github.com/dart-lang/js-interop/issues/86
  
  // Get a proxy to the JS object.
  var hug = new js.Proxy(context['Hug']);
  
  // Call the embrace method and pass in 10.
  var result = hug['embrace'](10);
  
  query('#output').text = result;
  
  // Call the patBack method and pass in a callback.
  hug['patBack'](new js.Callback.once((msg) {
    query('#output').appendText(' This just in: $msg');
  }));

}

The hug instance is accessed via a js.Proxy object. You can even pass a Dart function as a callback to a JavaScript function!

Summary

Use the Dart-JS interop library to access the billions of existing JavaScript libraries from Dart. Read the article for more details and see examples that use the Twitter API, Google Maps API, and the Google Charts API from Dart. The pub package is open source on Github, and is maintained by Googlers and engineers from the community.


Photo Credit: Gloson cc

Popular posts from this blog

Lists and arrays in Dart

The 29 Healthiest Foods on the Planet

Converting Array to List in Scala