views:

1065

answers:

3

Hi,

I just wanna learn how to read Iframe content in onLoad event of iframe and write it's content to the main page ? Thanks..

A: 
jQuery("#xiframe").load(function()
{
  var doc = null;
  try{
    doc = xiframe.document || xiframe.contentDocument || xiframe.contentWindow && xiframe.contentWindow.document || null;
  } catch(err) { 
    alert('error: ' + err.description); 
  }

  try {    
   if(!doc) {
     alert('error');
     return false;
   }
  } catch(err) {
    alert('error: ' + err.description); 
    return false;
  }

  alert(String(jQuery(doc.body).html());
}
andres descalzo
Thanks but actually the main problem is how to determine page load completes to get the content and write into main page content.
Braveyard
content "<html><head>...</head><body>...</body></html>" or "<body>...</body>"?
andres descalzo
A: 
  • parent document (the page on which the iframe is displayed)
  • child document (the page displayed inside the iframe)

If these two documents are in the same domain, you can use the window.parent.document object in the child document's onload event handler to access the parent document.

lance
+1  A: 

I have struggled with same this past day. It seems to matter how you access the iframe. If you use document.getElementById() you get an Iframe object, which has no onload event. However, if you access through window.frames[] array, for example

var iframeWindow = top.frames['iframeID'],

you get a window object, which does have onload event.

(ie uses the frame id attribute , but ff uses name attribute. So use both and make the same)

You can then assign

iframeWindow.onload=function(){iframeContent=iframeWindow.document.body.innerHTML;};

Notice, since iframeWindow is a window object, you use window syntax to access content.

Sheldon
I did it but it didn't work for me. Could you please send me your example if you don't mind.Thanks.
Braveyard
<script type="text/javascript"> function redisplay(){ var content = top.frames['fetch'].document.body.innerHTML; top.frames['display'].document.body.innerHTML = content; } </script> </head> <body><iframe id="display" name="display" style="width:600px; height:500px;border:solid 1px black;"></iframe><p></p><iframe src="page-in-same-domain" id="fetch" name="fetch" style="width:600px; height:500px;" onload="redisplay();"></iframe> </body>
Sheldon