【问题标题】:Show the HTML of a internet page显示网页的 HTML
【发布时间】:2018-07-27 10:53:22
【问题描述】:

我正在尝试编写一个脚本,其中有一个请求 URL 并显示该页面的 HTML 的按钮,但我无法获取页面的 HTML,我想知道这是否可能。

目前,这是我的代码:

function injectHTML() {

  //step 1: get the DOM object of the iframe.
  var iframe = document.getElementById('test_iframe');

  var html_string = prompt("Enter URL", "https://www.example.com");

  var iframedoc = iframe.document;
  if (iframe.contentDocument)
    iframedoc = iframe.contentDocument;
  else if (iframe.contentWindow)
    iframedoc = iframe.contentWindow.document;

  if (iframedoc) {
    // Put the content in the iframe
    iframedoc.open();
    iframe.src = html_string
    iframedoc.close();
  } else {
    //just in case of browsers that don't support the above properties.
    alert('Cannot inject dynamic contents into iframe.');
  }

}
<html>

<head>
</head>

<body>
  <h1>Internet Page</h1>
  <iframe id="test_iframe" src="about:blank" width=600 height=600></iframe>
  <div class='search'>
    <input id='search' type='button' value='Search ULR' onclick="javascript:injectHTML();" />
  </div>
  <style>
    .search {
      position: absolute;
      top: 23px;
      left: 530px;
    }
  </style>
</body>

<script language="javascript">
</script>

</html>

但它只显示互联网页面而不是 HTML 代码。

你能给我建议吗?

谢谢

【问题讨论】:

    标签: javascript html iframe


    【解决方案1】:

    您可以尝试发送 XmlHttpRequest 以“获取”HTML 页面,然后将响应设置为 innerText 到某个 div。

    【讨论】:

      【解决方案2】:

      不建议为此目的使用 iFrame。无论您使用什么标签,您都可以有多种选择:

      1. 使用 div 标签并在其中设置 html 的标签。 (推荐)例如:
        $(divElement).text('&lt;p1&gt;this p element not gonna be rendered&lt;/p1&gt;')

      2. 将 html 的标签放入 &lt;xmp&gt; 例如:
        <xmp id="rawHtml"> <p1>this p element not gonna be rendered</p1> </xmp>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-23
        • 1970-01-01
        • 2013-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多