Ved
Ved

Reputation: 3500

iFrame and Javascripts

I have the following page with iframes:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-   
transitional.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
     alert("test");
     elements = document.getElementById("reference").contentWindow.getElementLength();
     alert("test2");
 </script>
</head>
<frameset cols="20%,*">
   <frameset rows="25%,*">
      <frame src="./groups.html" name="types">
      <frame src="./entities.jsp" name="entities">
   </frameset>
   <frame src="./reference.jsp" name="reference" id="reference">
</frameset>
</html>

Inside reference.jsp, I have the following code :

<html>
<head>
   <script type="text/javascript">
       function getElementLength(){
            alert("in reference");
            elements=document.getElementByClassName("link");
            alert(elements.length);
        }
   </script>
 </head><body>...</body></html>

I checked earlier StackOverflow posts about using Javascript across frames and found that contentWindow does the trick but in this case, I only get first alert - "test" and the frame with id="reference" is never reached. I see the following error in Firebug:

document.getElementById("reference") is null
elements = document.getElement...").contentWindow.getElementLength(); 

Is there something I am missing, this seems to be a very straighforward usecase.

Upvotes: 1

Views: 231

Answers (2)

amd
amd

Reputation: 21512

Your document type is transitional which isn't support the framset try the below document type tag

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">

Upvotes: 0

Manse
Manse

Reputation: 38147

I think that the problem is that your script is executing before the frame is loaded ...

You could do the following to ensure the frame is loaded before the script is executed :

<script type="text/javascript">
function load() {
     alert("test");
     elements = document.getElementById("reference").contentWindow.getElementLength();
     alert("test2");
}
 </script>

<frameset cols="20%,*">
   <frameset rows="25%,*">
      <frame src="./groups.html" name="types">
      <frame src="./entities.jsp" name="entities">
   </frameset>
   <frame src="./reference.jsp" name="reference" id="reference" onload="load()">
</frameset>

I have added the onload="load()" attribute in the frame reference and wrapped your script in the load() function. This will cause the code to be executed once the reference frame is loaded.

Upvotes: 2

Related Questions