Reputation: 9289
How is it possible, to let the user download the current html page? The webpage loads the text using ajax, so my code doesn't works, because it downloads the original state of the page:
<a href="URL_OF_THIS_PAGE" download="page.html">Download</a>
Upvotes: 8
Views: 20187
Reputation: 473
<a onclick="this.href='data:text/html;charset=UTF-8,'+encodeURIComponent(document.documentElement.outerHTML)" href="#" download="page.html">Download</a>
How this works:
onclick
handler. The handler will be run when the anchor tag ("Download") is clicked.download
attribute set to the value page.html
. This tells the browser to download whatever the anchor tag's href
attribute is pointing to and give it the filename page.html
, rather than the default behaviour of visiting the link.this.href=
changes the href attribute of the tag. This is the URL to be visited when the anchor element ("Download") is clicked. This happens on the click handler, before the click event is bubbled up to the anchor tag itself.href
attribute of an anchor tag usually has a URL in it pointing somewhere. Here we are instead setting the href
to point to an inline value. We tell the browser what kind of value this is using the first part of the string: 'data:text/html;charset=UTF-8,'
. This tells the browser that the rest of the text will be a text/html
document with a UTF-8 charset encoding.encodeURIComponent(document.documentElement.outerHTML)
. So the href
attribute now points to an inline string representation of the HTML document itself.To summarize: when you click the anchor tag the click handler runs and the entire document is inserted as a downloadable inline file called "page.html" that is then downloaded when the click event bubbles up to the anchor tag itself.
Upvotes: 19