简体   繁体   中英

How to force download of "index.html" file via an <a> tag in HTML

I have an online configuration editor placed here . The configuration editor is made as a single-page file, ie 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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM