0

I'm using the below code inject some javascript into an iframe. It works fine however there's a (possible?) timing issue i am seeing. When the alert executes i see '0' however i know that after the injection jQuery is indeed loaded in the iframe (, i know that by executing the similar alert on click of a button in the iframe which correctly outputs '1').

let str = `<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script type="text/javascript">try{ alert(window.jQuery?'1':'0') } catch(e){ }</script>`

this.convertToNodes(str).forEach(eL => {
  iframe.contentDocument.head.appendChild(eL);
});

Anyway i can correctly inject the alert so that i see '1'?

noi.m
  • 3,070
  • 5
  • 34
  • 57
  • BTW i've also tried adding timeouts between adding of nodes, and it still outputs '0'. – noi.m Sep 18 '18 at 06:02
  • non inline scripts dynamically inserted into the document are always loaded as async. You can listen to their `onload` event to know when they've been fetched and executed. – Kaiido Sep 18 '18 at 06:03
  • ^ can you point to some pseudocode? Should i be listening for the event on object returned by appendChild? – noi.m Sep 18 '18 at 06:08
  • Well that's not clear at all where these strings come from to begin with, so it's hard to provide a good solution for you, but if you do `script_element_that_will_load_jQuery.onload = e => alert(window.jQuery?'1':'0'); document.head.appendChild(script_element_that_will_load_jQuery)` then it will alert `'1'`. But even, why do you need to insert jQuery in this iframe? Do you know you can pass the iframe's `contentDocument` as the `context` of `$(selector, context)`? You might be able to do all you want from your main context directly. – Kaiido Sep 18 '18 at 06:12
  • With strings if you mean str variable, it will be coming from a user input. The usecase if to basically load any library that user wants at runtime into the iframe. – noi.m Sep 18 '18 at 06:14
  • Thanks. the onload trick worked. Why don't you answer, so that i can pick your answer? – noi.m Sep 18 '18 at 06:24
  • @Kaiido onload doesnt seem to be called for . It seems to be called for – noi.m Oct 15 '18 at 01:52
  • onload will fire only for elements that do load some content. Inline ` – Kaiido Oct 15 '18 at 01:55

0 Answers0