15

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?

1

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

8 Comments

and suddenly, it does not work: claims "There is no such setter 'foo' in 'Proxy'" ...
yes :) first update of js went to 0.19 which continued to not work. After an edit restart, and a second update, I got 0.20 and it is all good again. Thanks again!
Callback is not mentioned in the linked document 'Calling Dart from JavaScript'. Was it removed?
Yes the answer was outdated.
What is the recommended way now ?
|
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);
}

4 Comments

this works well in native dart (dartium) but not in js compiled version (chrome, ff, ie..). Please check this screenshot. 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?
Seemed to work for me in Chrome and Dartium. I'll check again and report back.
Checked again and I can confirm that it's working in Dartium and Chrome.
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: 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!"
3

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);
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.