Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  12] [ 4]  / answers: 1 / hits: 14740  / 10 Years ago, mon, october 6, 2014, 12:00:00

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>

More From » html

 Answers
2
<a onclick="this.href='data:text/html;charset=UTF-8,'+encodeURIComponent(document.documentElement.outerHTML)" href="#" download="page.html">Download</a>

How this works:



  • We create an HTML anchor element with an onclick handler. The handler will be run when the anchor tag ("Download") is clicked.

  • The anchor tag has a 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.

  • Inside the handler the JavaScript 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.

  • The 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.

  • Finally, the entire source code of the current document is taken as a string and appended as the value of the inline document with 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.


[#42064] Saturday, October 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
donaldcristianl

Total Points: 114
Total Questions: 95
Total Answers: 110

Location: Bonaire
Member since Sat, May 27, 2023
1 Year ago
;