Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script tag inside iframe executes on parent dom

I write jQuery script inside my iframe to hide h1 inside the iframe

<iframe id = "preview" width="800" height="500">   
</iframe>

 <script>
var H = "<html><head><script>$(\'#hh\').toggle();<";
H+= "/script></head><body><h1 id='hh'>JavaScript</h1></body></html>";

 var previewFrame = document.getElementById("preview");
 var preview =  previewFrame.contentDocument ||  previewFrame.contentWindow.document;
 preview.open();
 preview.write(H);
 preview.close();
  </script>

but,the script can't see the elements inside the iframe. when I moved the element with id='hh' out of the iframe, the script works.

like image 291
Muhammad Sultan Avatar asked Sep 30 '22 15:09

Muhammad Sultan


1 Answers

It looks like you're trying to use jQuery inside the iframe for the script you're putting in the iframe, but you don't have jQuery in the iframe. The iframe is a whole different execution context. If you want to use jQuery in there, you have to load jQuery in there.

Also, you can't run a script that tries to modify the DOM from the <head> element. The DOM isn't loaded yet. You have to either move that script after the content in the <body> (e.g. right before </body>) or use $(document).ready(...) to run the script AFTER the DOM is ready.

OK, this is the sum of issues I found:

  1. You need jQuery in the iframe if you're going to use it there.
  2. You must use a separate <script> tag for loading jQuery. You can't use both a .src and a inline script in the same tag.
  3. You must use the proper $(document).ready(function() { your code here}) syntax.
  4. You must break apart the <script> and </script> that is in your JS string so the browser doesn't interpret it like '<scr' + 'ipt>'.

This works for me:

var H = '<html><body><h1 id="hh">JavaScript</h1>';
H += '<scr' + 'ipt src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></scr' + 'ipt>';
H += '<scr' + 'ipt>$(document).ready(function() {';
H += '$("#hh").hide();';
H += '});</scr' + 'ipt>';
H += '</body></html>';

var previewFrame = document.getElementById("preview");
var preview =  previewFrame.contentDocument ||  previewFrame.contentWindow.document;
preview.open();
preview.write(H);
preview.close();

I've broken up your H variable to make it more readable and easier to spot errors.

Working demo: http://jsfiddle.net/jfriend00/8L3KT/


FYI, this is the painful way to do this. Creating a full HTML document in JS is easy to make mistakes with.

like image 106
jfriend00 Avatar answered Oct 10 '22 15:10

jfriend00