How to get the entire document HTML as a string?

前端 未结 15 1941
暖寄归人
暖寄归人 2020-11-22 17:00

Is there a way in JS to get the entire HTML within the html tags, as a string?

document.documentElement.??
15条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 17:52

    I just need doctype html and should work fine in IE11, Edge and Chrome. I used below code it works fine.

    function downloadPage(element, event) {
        var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    
        if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
            document.execCommand('SaveAs', '1', 'page.html');
            event.preventDefault();
        } else {
            if(isChrome) {
                element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('' + document.documentElement.outerHTML));
            }
            element.setAttribute('download', 'page.html');
        }
    }
    

    and in your anchor tag use like this.

    Download entire page.
    

    Example

        function downloadPage(element, event) {
        	var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
        
        	if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
        		document.execCommand('SaveAs', '1', 'page.html');
        		event.preventDefault();
        	} else {
        		if(isChrome) {
                    element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('' + document.documentElement.outerHTML));
        		}
        		element.setAttribute('download', 'page.html');
        	}
        }
    I just need doctype html and should work fine in IE11, Edge and Chrome. 
    
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    
    

    Download entire page.

    Some image here

提交回复
热议问题