Question

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);
Was it helpful?

Solution

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();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top