Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File download not working on firefox

I have written this piece of code which is working perfect on Google Chrome and Opera but not working on Firefox

function onSaveJPG(url,n){
    var save = document.createElement('a');
    save.href = url;
    save.target = '_blank';
    save.download = 'Image no '+n+'.jpeg' || url;
    var event = document.createEvent('Event');
    event.initEvent('click', true, true);
    save.dispatchEvent(event);
    (window.URL || window.webkitURL).revokeObjectURL(save.href);
}

What is wrong? please guide me.

like image 948
newbie Avatar asked Nov 30 '13 17:11

newbie


People also ask

Why are my files not downloading?

Check your virus-scanning software for details about why the file was blocked. On Windows: Windows Attachment Manager could have removed the file you tried to download. To see what files you can download or why your file was blocked, check your Windows internet security settings.

How do I allow Downloads in Firefox?

Click the Firefox button, go to Options | Options | General and in the Downloads menu, checkmark the option "Always ask me where to save files". Click the Firefox button, go to Options | Options | General and in the Downloads menu, checkmark the option "'''Always ask me where to save files'''".


1 Answers

This should work (I figured it out by looking through the FileSaver.js code):

function onSaveJPG(url,n){
    var save = document.createElement('a');
    save.href = url;
    save.download = 'Image no '+n+'.jpeg' || url;
    var event = document.createEvent("MouseEvents");
        event.initMouseEvent(
                "click", true, false, window, 0, 0, 0, 0, 0
                , false, false, false, false, 0, null
        );
    save.dispatchEvent(event);
}

(the main problem is that you need to use a MouseEvent type event for firefox rather than an Event. This code will also work on Chrome).

like image 74
CpnCrunch Avatar answered Sep 22 '22 12:09

CpnCrunch