0

I'm trying to add a variable in a iframe, it works in Javascript way but it does not do what I want in Jquery way. Here is a jsfiddle.

Pure javascript way:

var iframeDocument = $('#iframe')[0].contentWindow.document;
var scriptObject = iframeDocument.createElement("script");
scriptObject.type = "text/javascript";
scriptObject.innerHTML = "var variable=9;";
iframeDocument.body.appendChild(scriptObject);

Result is okay in console (variable is set and equals to 9 and iframe context) :

enter image description here

And when I try to change the value of the variable in JQuery:

$('#iframe').contents().find('body').append($('<script type="text/javascript">').html('variable=10;'));

The variable is loaded in parent context and didn't change in iframe! enter image description here

I know Javascript way is often better than Jquery way but I am simply wondering why this doesn't work as expected.

Clemzd
  • 895
  • 2
  • 15
  • 35

1 Answers1

-2

You are missing </script>, which by the way, you cant't inject like that. Try this:

$('#iframe').contents().find('body').append($('<script type="text/javascript"><\/script>').html('var variable=10;'));
marioivangf
  • 178
  • 1
  • 9