0

I have an online configuration editor placed here. The configuration editor is made as a single-page file, i.e. an index.html file, which is hosted via the link.

I would like to be able to link to this configuration editor in a way that triggers a download of the index.html file upon clicking the link - instead of displaying it in the browser.

I was hoping to achieve this via below - but it seems to not work with an index.html file. Any suggestions how to resolve this via HTML or simple Javascript code?

<a href="https://[url]/index.html" download="editor">download here</a>
mfcss
  • 1,039
  • 1
  • 9
  • 25
  • I think you should implement a file downloader on your backend. If you are using NodeJS with Express you can check it here https://stackoverflow.com/questions/7288814/download-a-file-from-nodejs-server-using-express#7288883 – Lolpez Feb 27 '20 at 16:12
  • Since Browsers are usually quite eager to render html-pages, instead of downloading them, you'd probably have to enforce it by setting the `Content-Disposition: attachment` header when delivering the file from the backend. – Thomas Feb 27 '20 at 16:17
  • the download attribute doesn't take a value in html5, see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a – Mr. Dave Feb 27 '20 at 16:29
  • Thanks for the inputs. I'd even be happy with some simple vanilla javascript solution - but even that seems difficult for this edge case of downloading an index.html file. Any vanilla JS suggestions are appreciated! – mfcss Feb 27 '20 at 18:09

1 Answers1

0

I ended up with this solution - any inputs for improving it are welcome. Note that this solution results in a CORS issue unless the index.html is on the same domain, but since that happens to be the case for me it works as needed.

HTML:

<a href="#" id="download-editor" class="btn-white">Offline editor</a>

Javascript:

<script>
  window.onload = function() {
    var a = document.getElementById("download-editor");
    a.onclick = function() {

    var url = 'https://canlogger.csselectronics.com/simple-editor/index.html'

    fetch(url).then(function(t) {
      return t.blob().then((b)=>{
        var a = document.createElement("a");
        a.href = URL.createObjectURL(b);
        a.setAttribute("download", 'config-editor.html');
        a.click();
      }
      );
    });
    }
  }
</script>
mfcss
  • 1,039
  • 1
  • 9
  • 25