5

I'm trying to use the Downloads.jsm lib of Firefox (it's new in Firefox 23) in a jetpack addin.

var {Cu} = require("chrome"); //works fine
const {Downloads} = Cu.import("resource://gre/modules/Downloads.jsm"); //works fine

But executing either of these functions has no effect:

download = Downloads.createDownload({source: "http://cdn.sstatic.net", target: "/tmp/kaki.html"}); //download is an object but has no function "start"
Downloads.simpleDownload("http://cdn.sstatic.net","/tmp/kaki.html");

Documentation: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download

Do you have any idea, how to use these functions? I haven't found any examples on the web

balping
  • 7,518
  • 3
  • 21
  • 35

1 Answers1

6

The API functions return a promise, not the actual Download object.

In short, the following should work:

const {Downloads} = Cu.import("resource://gre/modules/Downloads.jsm", {});
var downloadPromise = Downloads.createDownload({source: "http://cdn.sstatic.net", target: "/tmp/kaki.html"})
downloadPromise.then(function success(d) {
  d.start();
});

Read up on promises, and to make dealing with them a lot more fun, also Task.jsm

The API did change quite a bit recently; what is documented is the current Aurora-25 or later API. The "old" API is documented within the source.

A more complete example with Firefox <25 support is available in this gist.

nmaier
  • 32,336
  • 5
  • 63
  • 78
  • Thanks for your answer! Now I'm closer to the solution. I discovered that the `saver: "copy"` parameter has to be set. In this case the success function is called and `d` is really a `Download` object. But `d.start()` has still no effect. – balping Aug 12 '13 at 20:40
  • The code I gave works for me verbatim in a chrome-privileged scratchpad (on OSX Nightly anyway), i.e. /tmp/kaki.html gets created with the correct contents. If you want more help, refine your question with more details and elaborate a bit. – nmaier Aug 12 '13 at 20:58
  • Could you please share your example at [Add-on builder](https://builder.addons.mozilla.org)? I copied your code exactly and it doesn't work. I'm running Ubuntu 12.04 and I really don't know what's wrong. I would be very grateful – balping Aug 12 '13 at 21:40
  • Turns out the API changed quite a bit between <=24 (Beta) >=25 (Aurora). I posted a more complete example, incl. version detection here: https://gist.github.com/nmaier/6220299 – nmaier Aug 13 '13 at 11:41
  • Thank you very much, your help was indispensable! This code works perfectly – balping Aug 13 '13 at 18:41