Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the content of _top window with content of iframe without reload page

Is it possible to replace the content of the browser window (_top frame) with the document loaded in an iframe, without issuing a new GET to load that document?

Something like this:

<html>
<head>
<script type="text/javascript" language="JavaScript">
$(document).ready(function() {
  $("#link").click(function() {
    // should present in the browser window the content of the iframe WITHOUT reload
    // even preserve javascript/head code
    $(document).html($("#frameDestination").html());
  });
});
</script>
</head>
<body>
<a id="link" href="#">full window</a>
<iframe id="frameDestination" src="http://www.some-random-site.com" width="900px" height="500px"></iframe>
</body>
</html>
like image 728
Gabriel Belingueres Avatar asked Nov 04 '22 05:11

Gabriel Belingueres


2 Answers

Use contents() when working with an iframe in jQuery.

$("#YourIframe").contents().find("html").html();

This is only going to work if the iframe is in the same domain as the parent.

like image 66
epascarello Avatar answered Nov 11 '22 05:11

epascarello


I haven't tested cross domain, but on the same domain I have this script working:

$(document).ready(function() {
  $("#link").click(function() {
    var iframeBody = document.getElementById("frameDestination").contentDocument,
    head = iframeBody['head'].innerHTML, 
    body = iframeBody['body'].innerHTML;
    $('body').html( body );
    $('head').html( head );
  });
});

In the latest Firefox, I'm even able to set a variable in a script tag in the frame, and see that value in _top after clicking the link.

like image 22
Rustavore Avatar answered Nov 11 '22 06:11

Rustavore