Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add JavaScript code into existing iFrame using jQuery?

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?

like image 486
Gandalf Avatar asked Aug 21 '13 23:08

Gandalf


People also ask

Can you put JavaScript in iframe?

Either your src-url will be used or your code between the iframe-tags will be used; never both. This means that there is no way to "embed a javascript into an iframe". The only way to get your script in there would be to add it to the source page that you're loading into the iframe.

Can you use jQuery in an iframe?

However, it's also possible to use a really simple jQuery to access the elements within the iFrame. Check it out below: $(document). ready(function(){ var iFrameDOM = $("iframe#frameID").

How do you embed JavaScript?

You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.


1 Answers

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).

var scriptTag = "<script>alert(1)<\/script>";
$("#iframe").contents().find("body").append(scriptTag);

Original solution

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 code (jsfiddle):

var scriptTag = "<script>alert(1)<";
scriptTag +=  "/script>";
console.log(scriptTag);
$("#iframe").contents().find("body").append(scriptTag);

Or (jsfiddle):

var scriptTag = "<script>alert(1)<"+"/script>";
$("#iframe").contents().find("body").append(scriptTag);
like image 97
Juan Mendes Avatar answered Oct 13 '22 16:10

Juan Mendes