Michael S.
Michael S.

Reputation: 305

How to make Firefox call a function in an extension whenever a file is downloaded?

Is there any way I can make Firefox call a JavaScript function in my extension whenever it completes a download (passing the path of the downloaded file)?

Upvotes: 2

Views: 384

Answers (2)

louisinhongkong
louisinhongkong

Reputation: 561

A copy/paste solution. Enjoy

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

Upvotes: 0

Michael S.
Michael S.

Reputation: 305

nvm, found it out by myself - if anybody needs: https://developer.mozilla.org/en/Code_snippets/Downloading_Files

Upvotes: 1

Related Questions