How do I get the HTML source from the page?

前端 未结 5 453
谎友^
谎友^ 2020-11-29 07:37

Is there a way to access the page HTML source code using javascript?

I know that I can use document.body.innerHTML but it contains only the code inside

相关标签:
5条回答
  • 2020-11-29 07:49

    For IE you can also use: document.all[0].outerHTML

    0 讨论(0)
  • 2020-11-29 07:54

    Use

    document.documentElement.outerHTML
    

    or

    document.documentElement.innerHTML
    
    0 讨论(0)
  • 2020-11-29 07:59

    One way to do this would be to re-request the page using XMLHttpRequest, then you'll get the entire page verbatim from the web server.

    0 讨论(0)
  • 2020-11-29 08:00

    This can be done in a one-liner using XMLSerializer.

    var generatedSource = new XMLSerializer().serializeToString(document);
    

    Which gives String

    <!DOCTYPE html><html><head>
    
    <title>html - javascript page source code - Stack Overflow</title>
    ...
    
    0 讨论(0)
  • 2020-11-29 08:03

    Provided that

    • true html source code is wanted (not current DOM serization)
    • and that the page was loaded using GET method,

    the page source can be re-downloaded:

    fetch(document.location.href)
        .then(response => response.text())
        .then(pageSource => /* ... */)
    
    0 讨论(0)
提交回复
热议问题