Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
when I load a file into an iframe, how do I access the html-items of the loaded file when the file uses body tag?

Example:
itest.html:
XML
<html>
<head>
<script>
function loadFrame()
 {var frm=document.getElementById('frmtest');
 frm.src="itest1.html";    // this alert works fine
 alert(frm.contentDocument.getElementById('whatever').innerHTML);
 frm.src="itest2.html";    // this alert does not work
 alert(frm.contentDocument.getElementById('whatever').innerHTML);
 }
</script>
</head>
<body>
<iframe id="frmtest"></iframe>
<button onclick='loadFrame();'>click me</button>
</body></html>
itest1.html:            <span id="whatever">THIS IS ME</span>
itest2.html:<html><body><span id="whatever">THIS IS ME</span></body></html>


The alert after loading itest1 shows me the innerHTML of the span.
However after loading itest2 (which uses html and body tags that are essential in my application) the alert shows that I can not access the items.
Does anybody know how I can acces the items of itest2.html?

Thanks Eke
Posted
Updated 27-Aug-10 2:41am
v2

It depends on domains of both iframe and page.

If domain is the same, page can access iframe through element.documentElement or something like that.
 
Share this answer
 
I found the real culprit: timing!!! But not the solution.

function loadFrame()
  {var frm=document.getElementById('frmtest');
  frm.src='itest1.html';
  if (frm.contentDocument)  
  alert(frm.contentDocument.getElementById('whatever').innerHTML);
  else  alert(frm.contentWindow.document.getElementById('whatever').innerHTML);
 }


works only for the tiny example itest1.html that I presented, but
never for a more substantial itest1.html.

However it always works after inserting a delay after loading and before accessing the elements as in the following example:
function loadFrame()
 {var frm=document.getElementById('frmtest');
  frm.src='itest1.html';
  alert('delay'): // INSERTED DELAY AFTER LOADING OF itest1.html
  if (frm.contentDocument)
    alert(frm.contentDocument.getElementById('whatever').innerHTML);
  else    alert(frm.contentWindow.document.getElementById('whatever').innerHTML); 
 }


Apparently the elements in itest1.html (such as id=whatever) do not exist immediately after the command frm.src=..., but only after a delay.
So maybe I should have rephrased my problem as "how to access the elements of a document loaded into an iframe" into "when(how) to access....".

Anybody recognizes this observation and how did you deal with it?

Thanks in advance......Eke
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900