Marc
Marc

Reputation: 1

How to set the src of an iframe to the current visited site using java script?

I would like to take a snapshot of the current visited site at a fixed resolution independent of client web-browser resolution. Therefor I would like to load the active site in an hidden iframe with that fixed resolution and take the snapshot from there.

Now my question is: How can I load the same site I am currently on in an iframe. Loading other pages works fine, but yet I was not able to load the same site in the iframe.

Is this some security issue?

Upvotes: 0

Views: 870

Answers (2)

Stano
Stano

Reputation: 8949

Tested the nested iframe, where its .src is equal to document.href.url in different browsers. Only Chrome allows such iframe embedded in the first level, other browsers prevent the above described recursion and leave the iframe empty. (As a side note, also it looks like Firefox and Opera allow at most 10 respectively 20 different nested iframes, other browsers like Google Chrome and Explorer add iframes ad infinitum.) You can use the following code to embed the parent page in the iframe, via the slightly modified url:

function load_iframe(addr) {
    var iframe = document.getElementById('iframe1');
    if (addr == document.location.href) {
        if (addr.indexOf('?') == -1) {
            addr += '?dummy_string';
        } else {
            addr += '&dummy_string';
        }
    }
    iframe.src = addr;
}

HTML example:

<a href="" onclick="event.preventDefault();load_iframe(this.href);">This page</a>
<iframe id="frame1" src="" style="width:100%; height:500px" />

The test script is here.

Upvotes: 1

James Westgate
James Westgate

Reputation: 11444

Something like

if (!document.getElementById('hiddenFrame') {
document.appendChild('<iframe id="hiddenFrame" src='+document.location+' style="display:none"'/>); }

Place the script at the bottom of the page just before closing BODY tag, or use a library like jQuery.

Upvotes: 0

Related Questions