View Full Version : Appending Javascript snippet via Javascript

01-17-2012, 06:55 AM
I want to insert this js snippet

function addText(smiley) {
document.getElementById('message').value += " " + smiley + " ";
return false;

to a loaded iframe with name&id chtifrm. I can access it & change embed something in its html via using something like:

$(parent.chtifrm.document.body).append('<div id=\"smly\" style=\"cursor:pointer;float:left;top:200px;display:none;position:absolute;\"><\/div>');

parent.chtifrm.document.getElementById('chatbox_option_disco').style.display == 'none'

but how do I insert js in the head of loaded iframe?

Philip M
01-17-2012, 07:17 AM
If the iframe does not originate in your domain, you can't. Security. Simply stated, the Same Origin Policy states that JavaScript code running on a web page may not interact with any resource not originating from the same web site.

All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

01-17-2012, 10:29 AM
yes sir I know that ...the iframe is of the same domain...but that wasn't the question. The question was that how do we insert a javascript snippet in the head section of any webpage...in my case the webpage was loaded in an iframe #chtifrm.

01-17-2012, 10:41 AM
Like this

var iframeDoc = document.getElementById('chtifrm').contentWindow.document;
var iframeHead = iframeDoc.getElementsByTagName('head')[0];
var newScript = iframeDoc.createElement('script');
newScript.innerHTML = "var whatever_your_code_is = 5;";
newScript.type = "text/javascript";

01-17-2012, 11:48 AM
sir like this:
only a part of it I need clarification

newScript.innerHTML = "function addText(smiley) {\n document.getElementById(\'message\').value += \" \" + smiley + \" \";\n document.getElementById(\'message\').focus();\n return false;\n}";

Philip M
01-17-2012, 11:53 AM
If the iframe is in the same domain, why do you not simply add the script to the page directly?

01-18-2012, 07:55 PM
ahh thnx devnull; your code works besides I have learned something new...thnx again