Search code examples
javascripthtmlcanvastodataurl

Javascript download not working in Firefox and IE


I am downloading the image. It is only working in Chrome not in Firefox or IE.

        var a = document.createElement('a');
        a.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
        a.download = 'Post-ITIE.jpg';
        a.click()

Can anyone help me how can it be working for all browsers.

JsFiddle example

Help would be highly appreciated. Thanks


Solution

  • var fileName = 'Post-ITIE.jpg';
    
    if ('msToBlob' in canvas) { // IE10+
      var blob = canvas.msToBlob();
      navigator.msSaveBlob(blob, fileName);
    } else {
      var a = document.createElement('a');
      a.setAttribute('href', canvas.toDataURL());
      a.setAttribute('target', '_blank');
      a.setAttribute('download', fileName);
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    

    It does a couple of thing differently than the code originally provided:

    • It checks if the msToBlob method is present to support downloading the file in Internet Explorer.
    • It adds a target=blank to the link element. This makes sure that the image is displayed, even if the browser doesn't support the download attribute.
    • It adds the link to the document so that the .click() actually works in Firefox and removes it afterwards.