It may work better if you create a new script element and add that to the parent.
See this post for more information: document.createElement('script') vs <script src="">
This is an example copied from the accepted answer in the above link.
var s = document.createElement('script');
s.src = "...";
document.getElementsByTagName("head")[0].appendChild(s);
The src property is the URL containing the script.
To add the script content to the element directly from a string you need the answer from:
Adding <script> element to the DOM and have the javascript run?
So your question example code would be:
var scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
var code = 'alert(1);';
try {
scriptTag.appendChild(document.createTextNode(code));
$("#iframe").contents().find("body").appendChild(scriptTag);
} catch (e) {
scriptTag.text = code;
$("#iframe").contents().find("body").appendChild(scriptTag);
}
Also see this post for more details on how to attach the script element: document.head, document.body to attach scripts