문제

는 방법이 있 JS 을 얻을 전체 내에서 HTML html 태그의 문자열로?

document.documentElement.??
도움이 되었습니까?

해결책

MS가 추가되었습니다 outerHTML 그리고 innerHTML 얼마 전에 속성.

에 따르면 MDN, outerHTML Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile 및 Safari Mobile에서 지원됩니다. outerHTMLDom Parsing 및 Serialization 사양.

보다 퀴크 스 모드 브라우저 호환성에 대한 호환성. 모든 지원 innerHTML.

var markup = document.documentElement.innerHTML;
alert(markup);

다른 팁

넌 할 수있어

new XMLSerializer().serializeToString(document)

브라우저에서 IE 9보다 새로운 브라우저

보다 https://caniuse.com/#feat=xml-serializer

나는 믿는다 document.documentElement.outerHTML 당신을 위해 그것을 반환해야합니다.

에 따르면 MDN, outerHTML Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile 및 Safari Mobile에서 지원됩니다. outerHTMLDom Parsing 및 Serialization 사양.

MSDN 페이지에서 outerHTML 재산 IE 5+에서 지원됩니다. Colin의 답변은 W3C Quirksmode 페이지와 연결되며, 이는 크로스 브라우저 호환성 (다른 DOM 기능의 경우)을 잘 비교할 수 있습니다.

나는 반환 된 것을보기 위해 다양한 답변을 시도했습니다. 최신 버전의 Chrome을 사용하고 있습니다.

제안 document.documentElement.innerHTML; 반환 <head> ... </body>

개비의 제안 document.getElementsByTagName('html')[0].innerHTML; 똑같이 돌아 왔습니다.

제안 document.documentElement.outerHTML; 반환 <html><head> ... </body></html>그것은 'doctype'과는 별개입니다.

DocType 객체를 검색 할 수 있습니다 document.doctype; 이것은 문자열이 아닌 객체를 반환하므로 html5까지 모든 문학에 대한 문자열로 세부 사항을 추출 해야하는 경우 여기에 설명되어 있습니다. JavaScript가있는 문자열로 HTML의 DocType를 얻습니다

나는 html5 만 원했기 때문에 다음은 전체 문서를 만들기에 충분했습니다.

alert('<!DOCTYPE HTML>' + '\n' + document.documentElement.outerHTML);

당신은 또한 할 수 있습니다 :

document.getElementsByTagName('html')[0].innerHTML

당신은 doctype 또는 html 태그를 얻지 못하지만 다른 모든 것은 ...

document.documentElement.outerHTML

아마도 IE :

>     webBrowser1.DocumentText

1.0에서 FF UP :

//serialize current DOM-Tree incl. changes/edits to ss-variable
var ns = new XMLSerializer();
var ss= ns.serializeToString(document);
alert(ss.substr(0,300));

FF에서 작동 할 수 있습니다. (소스 텍스트의 시작 부분에서 처음 300자를 표시합니다.

그러나 FF의 정상적인 "저장"-디 알로그는 페이지의 현재 상태를 저장하지 않고 오히려 원래로드 된 x/h/tml-source-text !! (SS를 일부 온도 파일로 포스트 업 및이를 리디렉션하면 이전에 변경 사항/편집 기능이있는 저장 가능한 소스 텍스트를 제공 할 수 있습니다.)

FF는 "백"에서 좋은 회복과 "Save (AS) ... 입력과 같은 필드의 경우 TextRea 등, Contenteditable/ DesignMode의 요소가 아닙니다 ...

xhtml- resp. XML-File (Filename-Extension뿐만 아니라 MIME-TYPE!), opport.open/write/close를 사용할 수 있습니다. FF의 파일/저장 menue에서 사용자의 저장 디 알로그에 저장되는 소스 레이어에 대한 콘텐츠. 보다:http://www.w3.org/markup/2004/xhtml-faq#docwrite resp.

https://developer.mozilla.org/en-us/docs/web/api/document.write

X (HT) ML의 중립에서 중립적 인 "View-Source : http : // ..."를 시도해보십시오. iframes에 액세스하려면 (Script-Made!?) iframe의 SRC-Attrib의 값으로 사용하십시오. FF의 문서 :

<iframe-elementnode>.contentDocument, appr. 예를 들어 'TextContent'와 같은 회원. '몇 년 전과 크롤링을 좋아하지 않습니다. 여전히 긴급한 필요가 있다면, 이것을 언급하면서, 나는 ...

document.documentElement.innerHTML

나는 항상 사용합니다

document.getElementsByTagName('html')[0].innerHTML

아마 올바른 방법은 아니지만 볼 때 이해할 수 있습니다.

사용 document.documentElement.

여기에 같은 질문이 있습니다.https://stackoverflow.com/a/7289396/2164160

외부에서 물건을 얻으려면 <html>...</html>, 가장 중요한 것은 <!DOCTYPE ...> 선언, 문서를 걸을 수 있습니다. childnodes, 각각을 문자열로 바꿉니다.

const html = [...document.childNodes]
    .map(node => nodeToString(node))
    .join('\n') // could use '' instead, but whitespace should not matter.

function nodeToString(node) {
    switch (node.nodeType) {
        case node.ELEMENT_NODE:
            return node.outerHTML
        case node.TEXT_NODE:
            // Text nodes should probably never be encountered, but handling them anyway.
            return node.textContent
        case node.COMMENT_NODE:
            return `<!--${node.textContent}-->`
        case node.DOCUMENT_TYPE_NODE:
            return doctypeToString(node)
        default:
            throw new TypeError(`Unexpected node type: ${node.nodeType}`)
    }
}

이 코드를 다음과 같이 게시했습니다 Document-outerhtml NPM에서.


편집하다 참고 위의 코드는 함수에 따라 다릅니다 doctypeToString; 그 구현은 다음과 같습니다 (아래 코드는 NPM에 게시됩니다. Doctype-to-string):

function doctypeToString(doctype) {
    if (doctype === null) {
        return ''
    }
    // Checking with instanceof DocumentType might be neater, but how to get a
    // reference to DocumentType without assuming it to be available globally?
    // To play nice with custom DOM implementations, we resort to duck-typing.
    if (!doctype
        || doctype.nodeType !== doctype.DOCUMENT_TYPE_NODE
        || typeof doctype.name !== 'string'
        || typeof doctype.publicId !== 'string'
        || typeof doctype.systemId !== 'string'
    ) {
        throw new TypeError('Expected a DocumentType')
    }
    const doctypeString = `<!DOCTYPE ${doctype.name}`
        + (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
        + (doctype.systemId
            ? (doctype.publicId ? `` : ` SYSTEM`) + ` "${doctype.systemId}"`
            : ``)
        + `>`
    return doctypeString
}

DocType HTML이 필요하며 IE11, Edge 및 Chrome에서 잘 작동해야합니다. 아래 코드를 사용하여 잘 작동합니다.

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('<!doctype html>' + document.documentElement.outerHTML));
        }
        element.setAttribute('download', 'page.html');
    }
}

그리고 당신의 앵커 태그에서 이와 같은 사용.

<a href="#" onclick="downloadPage(this,event);" download>Download entire page.</a>

예시

    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('<!doctype html>' + 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.

<p>
<a href="#" onclick="downloadPage(this,event);"  download><h2>Download entire page.</h2></a></p>

<p>Some image here</p>

<p><img src="https://placeimg.com/250/150/animals"/></p>

당신은 반복하는 문서를 통해 childNodes 및 outerHTML 내용입니다.

VBA 에서 그것은 다음과 같습니다

For Each e In document.ChildNodes
    Put ff, , e.outerHTML & vbCrLf
Next e

이를 사용하여 얻을 수 있습의 모든 요소가 웹 페이지함 < !DOCTYPE>노드를 존재하는 경우

올바른 방법은 실제로 :

WebBrowser1.documentText

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