14

I'm a bit of a newb to dart, and trying to get my feet wet by writing some library functions in it.

While I've had no problem calling javascript functions from dart, I'd love to be able to call dart functions from javascript, but so far, I'm not having much like.

For example, I'd love to be able to expose some basic functions from dart, for example like so:

main() {
  String foo() {
    return "bar!";
  }

  js.scoped(() {
    js.context.foo = foo;
  });
}

and then be able to call them from javascript, like so:

<script>
  window.onload = function() {
    alert("foo() = " + foo());
  }
</script>

Is something like this even possible?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Mason Bryant
  • 1,372
  • 14
  • 23

3 Answers3

14

No problem ! see Calling Dart from JavaScript.

In your case :

import 'dart:js' as js;
main() {
  String foo() {
    return "bar!";
  }

  js.context['foo'] = foo;
}
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
4

In Dart 1.20 I had to add allowInterop()

import 'dart:js' as js;
main() {
  String foo() {
    return "bar!";
  }

  js.context['foo'] = allowInterop(foo);
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • this works well in native dart (dartium) but not in js compiled version (chrome, ff, ie..). Please check this [screenshot](http://data.itpro.cz/dart_js.png). When I remove allowInterop, it works even in js compilled version. I am using Dart 1.19.1. Is it something that was fixed in 1.20? – Ivo Skalický Sep 12 '16 at 07:49
  • Seemed to work for me in Chrome and Dartium. I'll check again and report back. – Günter Zöchbauer Sep 12 '16 at 07:50
  • Checked again and I can confirm that it's working in Dartium and Chrome. – Günter Zöchbauer Sep 13 '16 at 09:53
  • Thank you for verification. I have tried to create empty sample polymer project, containing only code in screenshot above and it does not work for me with use of allowInterop (works in Dartium but not in IE, FF, Chrome). I have tested in in multiple browsers on multiple computers. You can test it yourself if you want to: http://data.itpro.cz/dart_allowinterop. When you press F12 in Chrome and type: foo() you will get an error, if you type foo2() it writes "bar2!" – Ivo Skalický Sep 13 '16 at 12:38
2

In Dart 2.3.0 I had to tweak the solution just a bit for allowInterop to play nice.


    import 'dart:js' as js;
    main() {
      String foo() {
        return "bar!";
      }

      js.context['foo'] = js.allowInterop(foo);
    }

rkunboxed
  • 168
  • 1
  • 10