Download files using the Firefox add-on

I am new to the development of Firefox add-ons, and so far everything is going well, but I was fixated on how, in fact, to download a file from the Internet, get a URI and save it to disk. The Mozilla MDN documentation contains information on how to upload files, but the download section is empty and not yet written. Unfortunately, I did not find any documentation that describes how to do this.

Does anyone know of relevant documentation on how to do this?


Old Facebook Download Album Adder uses this function call in its overlay JavaScript:

saveURL(images[i].replace(/\/s/g, "/n"), null, null, false, true, null); 

Obviously, the first argument is a URI request. The saveURL function saveURL not defined anywhere, so I guess its API extension function. I tried this in my new add-on and it works. However, I would like to know what the other arguments mean.

+7
source share
4 answers

The standard way to do this is with nsIWebBrowserPersist:

 var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]. createInstance(Ci.nsIWebBrowserPersist); persist.saveURI(serverURI, null, null, null, "", targetFile); 

See https://developer.mozilla.org/en/Code_snippets/Downloading_Files for more details.

+5
source
+3
source

Here you can easily copy / paste the option for those who are looking for a quick solution without any additional clutter. Put it in your main.js and change the file name, directory and url.

 function DownloadFile(sLocalFileName, sRemoteFileName) { var saveToDirectory = 'C:\\Users\\louis\\downloads\\'; var chrome = require("chrome"); var oIOService = chrome.Cc["@mozilla.org/network/io-service;1"].getService(chrome.Ci.nsIIOService) var oLocalFile = chrome.Cc["@mozilla.org/file/local;1"].createInstance(chrome.Ci.nsILocalFile); oLocalFile.initWithPath(saveToDirectory + sLocalFileName); var oDownloadObserver = {onDownloadComplete: function(nsIDownloader, nsresult, oFile) {console.log('download complete...')}}; var oDownloader = chrome.Cc["@mozilla.org/network/downloader;1"].createInstance(); oDownloader.QueryInterface(chrome.Ci.nsIDownloader); oDownloader.init(oDownloadObserver, oLocalFile); var oHttpChannel = oIOService.newChannel(sRemoteFileName, "", null); oHttpChannel.QueryInterface(chrome.Ci.nsIHttpChannel); oHttpChannel.asyncOpen(oDownloader, oLocalFile); } DownloadFile("saveAsThis.mp3","http://domain.com/file.mp3"); 
+1
source

As of 2015, the APIs for managing downloads (start, stop, etc.) have changed since the answer to this question. New APIs (links to MDN documentation):

0
source

All Articles