0

So let's say I have a link

<a href="http://URL"></a>

In place of this link, I want to instead show an IFRAME that contains the contents of the link. Example:

<iframe src="http://URL"></iframe>

The width of this iframe would be 100% and the height of the iframe would dynamically be calculated to equal the height of the resulting page (aka the http://URL).

How would I do this with a pure Javascript solution?

kevinkt
  • 735
  • 12
  • 24

1 Answers1

1

You could try this, but it works only within the same domain name. It is security restrictions

<html>
<body>
    <div>
        <a href="http://example.org" class="frame">example.org</a>
    </div>
    <script>
        var links = document.getElementsByClassName('frame');
        for (var i = 0; i < links.length; i++) {
            var frame = document.createElement("iframe");
            frame.setAttribute('src', links[i].getAttribute('href'));
            frame.setAttribute('class', links[i].getAttribute('class'));
            frame.style.width = "100%";
            frame.onload = function() {
                frame.style.height = frame.contentWindow.document.body.scrollHeight + "px";
            };

            links[i].parentNode.replaceChild(frame, links[i]);
        }
    </script>
</body>
</html>
Serge
  • 321
  • 3
  • 14
  • How would I change it so there's no domain restriction? – kevinkt May 06 '16 at 08:02
  • You could embed javascript code on remote server (or change server response headers) if it is yours, but I suppose it's not the case? Then try the following library, I didn't actually use it: https://github.com/davidjbradshaw/iframe-resizer – Serge May 06 '16 at 09:54