0

Apologies for the confusing title.

I've got a webpage with a friendly iframe in it, and the iframe contains a script tag inside it. Essentially it looks like this:

<iframe src="Javascript:'<div id=\'target\'></div><script src=\'appendStuff.js\'><\/script>'"></iframe>

appendStuff.js loads jQuery on document, and then does an operation like the following:

doc = document;  // the iframe's document
$('<h1>Loaded!</h1>').appendTo('#target', doc);

This works just fine. However, to fix another bug in appendStuff.js we needed to move jQuery and load it on window.top.document, instead of document which is inside the iframe.

Now, the .appendTo('#target', doc) call silently fails, and nothing gets appended.

This is incredibly confusing because just selecting $('#target', doc) seems to work just fine.

Does anyone know if this is actually broken, if I'm doing something wrong, or if there's some way to work around this issue?

Mordred
  • 3,734
  • 3
  • 36
  • 55

1 Answers1

0

jQuery kicks in on document ready. When you say "to fix another bug in appendStuff.js", my first guess is that the bug there had something to do with that code trying to run before document ready, and therefore, before jQuery itself was loaded. When you're then trying to select $('#target', doc) manually - in the console, I presume - you're doing it after the page has loaded, therefore after document ready.

So first, take a look at your appendStuff.js. At a guess, you should be wrapping it with $(function(){ ... }); to get your load order problems fixed. You also should take a look at How can I detect whether an iframe is loaded? and How to check if iframe is loaded or it has a content? , as it sounds like you really should have all this logic in the parent, rather than shoehorning it into the iframe.

Community
  • 1
  • 1
BrianFreud
  • 7,094
  • 6
  • 33
  • 50
  • Unfortunately, not the issue. Everything is already wrapped to wait for document ready. Yes, I was testing that code in the console, but it also works just fine on the very next line in the actual source code. Obviously it would all be in the parent if I could put it there, but appendStuff.js actually loaded by other websites, and often times it's loaded inside an iframe which is the situation we're in now. I'll update my question with this information too. – Mordred Jun 21 '16 at 20:52