Kenneth Bo Christensen Kenneth Bo Christensen - 2 months ago 5
Javascript Question

Can't keep script isolated to iframe

I have a script inside an iframe that looks for an element with jquery, but when it runs, it only finds an element outside the iframe - not the element that is inside the iframe.

Please help me with isolating the script to only be excecuted inside the iframe.

I have the example here: my example

A picture that illustrates my example:
enter image description here

How I create the iframe as showned in my linked example:


//Head to iframe:
var head = '<meta charset="utf-8">' +
'<meta http-equiv="X-UA-Compatible" content="IE=edge">' +
'<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">' +
'<script src="http://code.jquery.com/jquery-1.10.2.js"><\/script>';

//Body to iframe that contains a script that I would like only to run inside the iframe:
var body = '<code id="codeInside">code tag inside</code>' +
'<script>var codeTag = $("code").text("TAG FOUND!!");<\/script>';

//Insert the iframe:
var iframe = $('<iframe src="javascript:\'\'">').appendTo($('body'));
iframe.contents().find('head').html(head); //Append head til the iframe
iframe.contents().find('body').html(body); //Append body to the iframe

Answer

I got it: a working solution

//Head to iframe:
    var head = '<head><meta charset="utf-8">' +
      '<meta http-equiv="X-UA-Compatible" content="IE=edge">' +
      '<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">' +
      '<script src="http://code.jquery.com/jquery-1.10.2.js"><\/script></head>';

    //Body to iframe that contains a script that I would like only to run inside the iframe:
    var body = '<body><code id="codeInside">code tag inside</code>' +
      '<script>var codeTag = $("code").text("TAG FOUND!!"); console.log("codeTag", codeTag);<\/script></body>';

    //Insert the iframe:
    var iframe = $('<iframe src="javascript:\'\'">').appendTo($('body'));

    var doc = iframe[0].contentWindow.document;
    doc.open();
    doc.write(head);
    doc.write(body);
    doc.close();
Comments