Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download the current document's innerHTML as a file?

Is there a way I could download the current document's innerHTML as file programmatically?

I've made the following attempt without success. It does download the current document's source, however that's not what I am looking for, since I want to preserve any post-load document modifications.

 var save = document.createElement('a');
 save.href = "my location href.attr";
 save.target = '_blank';
 save.download = fileName || 'unknown';

 var event = document.createEvent('Event');
 event.initEvent('click', true, true);
 save.dispatchEvent(event);
like image 406
saeedhbi Avatar asked Nov 10 '13 01:11

saeedhbi


People also ask

How can I download current page in HTML?

You can also right-click anywhere on the page and select Save as or use the keyboard shortcut Ctrl + S in Windows or Command + S in macOS. Chrome can save the complete web page, including text and media assets, or just the HTML text.

How do I get data from innerHTML?

First, select the <ul> element by its id ( menu ) using the getElementById() method. Then, get the HTML content of the <ul> element using the innerHTML .

Why you shouldn't use innerHTML?

'innerHTML' Presents a Security Risk The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.


1 Answers

Perhaps something like this? It's probably not very cross-browser however, but it works in Chrome.

function downloadCurrentDocument() {
  var base64doc = btoa(unescape(encodeURIComponent(document.documentElement.innerHTML))),
      a = document.createElement('a'),
      e = new MouseEvent('click');

  a.download = 'doc.html';
  a.href = 'data:text/html;base64,' + base64doc;
  a.dispatchEvent(e);
}
    
downloadCurrentDocument();
like image 195
plalx Avatar answered Oct 19 '22 17:10

plalx