2

This should be simple, but I just can't seem to wrap my head around it.

So I have my dartFile.dart and then I have my javaScriptFile.js. How do I link these two so that I can call JavaScript functions declared in my javaScriptFile.js from my dartFile.dart?

I tried to follow the explanation provided in this post, but I guess it was too vague for me :/

Edit: Here's what I tried:

In my javaScriptFile.js, there is nothing but this simple function:

function myFunction() {
  return 4;
}

In my dartFile.dart, there is only this blob of code:

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

void main() {
  print(js.context.myFunction());
}

Following the instructions in the post I mentioned, I added dependencies for js in the pubspec.yaml file. Basically I'm exactly where the asker of the original question was - I can call basic JavaScript functions like alert, but wehn I try to call my function declared in the javaScriptFile.js, I get a 'NoSuchMethodError'

4
  • Your question should be much more specific about what you try to accomplish and show code that demonstrates what you have tried, and what error you got. Commented Aug 9, 2014 at 17:53
  • You make a fine point. I tried to keep it simple, but perhaps I should have been more specific. Is it better now? Commented Aug 9, 2014 at 18:09
  • Why do you need JS if you already can use Dart? Commented Aug 9, 2014 at 18:22
  • Heh, only now that you asked I realized how this must look :D I need to use external libraries written in JavaScript (by someone else of course). I used my own JavaScript file here in this example purely for learning purposes - in order to simplify things as much as possible. Commented Aug 9, 2014 at 18:37

1 Answer 1

3

You can just do it like this:

  1. Make sure you include JS before .dart files or make sure all JS files are loaded before running Scripts from Dart

  2. Contents of the dart file:


import 'dart:js';

void main() {
  var ret = context.callMethod('myFunction', ['a', 'b']);
  var inst = new JsObject(context['someClass'], ['instance']); 
  print(inst);
}
  1. my JS File:

function myFunction() {
  console.log(arguments);
}

function someClass(a) {
  this.a = a;
}

This should give you output like

[object Arguments] // from console.log
[object Object]    // from print()

Regards, Robert

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works perfectly now! I was puzzled by the "Make sure you include JS before .dart files" for a second, but then I realized you meant the <script src="JavaScriptFile.js"></script> line in the .html file. (And thus, I'm writtin this comment in case anyone else get stuck where I did)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.