문제

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);
도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top