0

I'm trying to write a script where there is a button that asks for a URL and shows the HTML of that page, but I can't manage to get the HTML of the page and I wonder if it is possible.

For the moment, here is my code:

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>

But it only shows the internet page and not the HTML code.

Can you give me advice?

Thanks

Ullas Hunka
  • 2,119
  • 1
  • 15
  • 28
cha3097
  • 25
  • 6

2 Answers2

2

You can try to send an XmlHttpRequest to "GET" the HTML page and then with the response, set it as innerText to some div.

Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
0

It's not recommended to use iFrame for this purpose. Despite of what tag you are using you can have multiple choices:

  1. Use div tag and set your html's tags inside that. (recommended) e.g:
    $(divElement).text('<p1>this p element not gonna be rendered</p1>')

  2. Put your html's tags inside <xmp> e.g:
    <xmp id="rawHtml"> <p1>this p element not gonna be rendered</p1> </xmp>

Mahyar Zarifkar
  • 176
  • 1
  • 12