Tony_Henrich
Tony_Henrich

Reputation: 44155

Getting a reference to a nested frame object doesn't work everytime in IE8. It works when adding an alert()!

I have an odd problem with IE8. I am trying to get a reference to a frame (same domain) object. The frame resides inside an iframe. The iframe resides deep inside multi level div's. The whole html is an output from an ASP.NET server control. jQuery code to get the reference is jQuery(top.window.frames['the_iFrame'][1].document).contents()[0]. The code resides in a jQuery ready() function. (The iframe id is generated dynamically and there's code to get the id).

This works everytime in Firefox. However in IE8 sometimes the object is empty. BUT if I place a dummy alert() just before the above jQuery code, it works everytime in IE8. I don't know why but my guess it has to do with suspended code execution? An alert() won't cut it so I tried to get the reference in a loop which contains a delay thinking maybe it needs some time but that didn't help.

Questions: Why placing an alert makes the code work in IE? Is there a way to fake the alert's good side effect with something non visual? Why isn't it working reliably in IE?

Upvotes: 1

Views: 505

Answers (1)

Pointy
Pointy

Reputation: 413826

You're probably trying to access the <iframe> contents before it's loaded and ready. Your outer-level "ready" handler will not wait for the nested <iframe> to load.

A couple of options:

  1. Probably the most reliable thing to do, if you can manage it, is to flip around the responsibilities. Have the page inside the frame push information up to the parent page from its own "ready" handler.

  2. If you can't affect changes to the page in the <iframe>, then you could poll until it's ready

    function waitForFrame(whenReady) {
      function doWait() {
        var obj = jQuery(top.window.frames['the_iFrame'][1].document).contents()[0];
        if (obj)
          whenReady(obj);
        else
          setTimeout(doWait, 100);
      }
      setTimeout(doWait, 100);
    }
    

Upvotes: 1

Related Questions