Sunday, August 6, 2017

Get You Some Of That: Creating a button that allows you to save a document

This will be a quick, fun post to solve a relatively simple problem - saving a web page. Of course a person could use the native browser controls, but where's the fun in that?! So, here we go.

First, you'll want something that the user can activate to trigger the 'save'. We'll assume the user has JavaScript enabled, because this won't work otherwise. In reality, if you were going to add this to your page, you'd want to add the interface component using JavaScript so it wouldn't appear if it weren't going to work...but, like I said, we're going to just make that assumption to save a little time by adding <button type="button" onClick="saveAs()">Save As...</button> to our document.

Next, we add the following script to our document...


JavaScript

<script>   function saveAs() {     var downloader = document.createElement('a'),       blob = new Blob([document.body.innerHTML], {type: 'text/html'}),       name = window.prompt('Please enter a filename', document.title);     if (name) {       downloader.download = name;       downloader.href = window.URL.createObjectURL(blob);       downloader.onclick = function (e) {         e.target.parentNode.removeChild(e.target);       };       document.body.appendChild(downloader);       downloader.click();     }   } </script>


Now, when you click it will automatically download the document as an HTML document, easy peasy lemon squeazy.

Happy coding.

No comments:

Post a Comment