I want to add a JavaScript snippet into an existing iFrame in the page using jQuery. I have the following code...
Code:
content = "<script>" + js_code + "</script>";
$('#iframe_id').contents().find('body').append(content);
But somehow this is not working. I checked some of the existing/related answers, and it seems jQuery does not quite recognize the script tags as...script tags. The iFrame is in the same domain/same port/same host, so there is no issue about cross-site scripting etc. How can I fix this?
As the iframe runs as it's own
window
, you will have to also inject the import of the jquery.js file.EDIT: So I played with this a bit more and here is what I came up with.
HTML
JS
This works, see here http://jsfiddle.net/WsCxj/.
So there are several points:
I am passing the entire content as one string. You have to prepend
data:text/html;charset=utf-8,
and then you can set your string as src of the iframe.I am adding the jquery.js file with an absolute path - This seems to be important, presumably because the frame has no path by itself as it's content is dynamically generated.
I split the script end tag like this
<" + "/script>
because at least firefox tries to end the actual script at this point. The cleaner approach would probably be to have the js as totally separate file.The problem is that the HTML parser gets confused if your script contains the closing script tag in it (
</script>
) and it closes the script tag prematurely.The solution is to escape the
/
in"<\/script>"
. This works because strings in JavaScript, (and some other languages), any invalid escape sequences are just ignored, so"\l"
is treated as"l"
, and"\/"
is treated as"/"
. The HTML parser, however, doesn't use a backslash to escape them so it doesn't get confused (credits to https://stackoverflow.com/users/405681/keaukraine).Original solution way
Break up that closing tag so you don't mess up the HTML parser. The other solutions on this page work because they never have the string
</script>
in their codehttp://jsfiddle.net/ALpjZ/2/
This was the simplest way I could make it work.
How about setting ajax refresh with js interval function to take any data stored in file/session etc. ?
It's surely not the most lightweight mode and it involves a tiny bit php, but can do the work.
You don't need add a tag script to execute javascript, you can do a function and apply iframe context...
using eval
Without eval
You need to escape the
/script
. It apears.Do like google analitcs for instance
replace the
script
and/script
with this escaped onesHope it helps.