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

旧巷老猫 提交于 2021-02-18 10:28:25

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/19885213/how-to-download-the-current-documents-innerhtml-as-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!