'Download text file or image throw javascript on Firefox

I'm trying to download a file using a http link. This is the code:

downloadFile: function (fileName, url) {
    var link = document.createElement('a');
    link.setAttribute('download', fileName);
    link.setAttribute('type', 'application/octet-stream');
    link.target = '_blank';
    link.href = url;

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);
}

This works on Chrome and Edge but not on Firefox. When I tried to download a text file or image, the browser opens a new tab this the file content rendered. I need that the browser open the default download window.

Is it possible?

This is an example of URL that I use: http://localhost:17671/docstmp/528d149e37467a53faeeeb0556901d87/ToDo.txt

I created this jsfiddle to demonstrate: jsfiddle.net/hp7yod85



Solution 1:[1]

The requested resource does not have Access-Control-Allow-Origin header set, and has X-Frame-Options header set to SAMEORIGIN to prevent loading into <iframe> element.

You can use YQL to retrieve content, then create a data URL of text content at returned results, then create an <a> element with href set to data URL. Returns expected result of opening dialog which prompts to open file within text editor or save file at firefox 47.

<!DOCTYPE html>
<html>
<body>
  <button onclick="downloadFile()">Test</button>
  <script>
  function downloadFile() {
    var request = new XMLHttpRequest();
    var url = 'https://query.yahooapis.com/v1/public/yql?q='
              + 'select * from html where '
              + 'url="http://www.ietf.org/rfc/bcp/bcp47.txt"&format=json&callback='
    request.open("GET", url);
    request.onload = function() {
      var data = JSON.parse(this.responseText).query.results.body.content;
      var a = document.createElement("a");
      a.href = "data:text/plain," + data;
      a.download = "bcp47.txt";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    request.send()
  }
  </script>
</body>
</html>

plnkr http://plnkr.co/edit/8JBBhVwIy0Icr2MaQZif?p=preview

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 guest271314