How to write a script tag inside a javascript code

2019-09-16 14:43发布

问题:

I have a javascript code which is called inside an iframe. I want to add a tag inside that javascript code and append the tag to the iframes parent body. This is my code to add the script tag and append to iframes parent body.

setTimeout(function () {
         var scriptTag = "<script>alert(1)<";
         scriptTag +=  "/script>";
         $("#iframe").contents().find("body").append(scriptTag);
    }, 5000);

the code isn't working it neither added the script tag nor showed any error

回答1:

Your scriptTag is a string and not an HTML element, so you are just appending the string. You have to use document.createElement

setTimeout(function () {
var scriptTag = document.createElement('script');
     scriptTag.src = 'alert(1)'
     $("#iframe").contents().find("body").append(scriptTag);
}, 5000);


回答2:

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



回答3:

Thanks guys for all the ans I did figured out a way to add the tag and append it to the iframe's parent body.

setTimeout(function () {                     
              var imported = document.createElement('script');
              imported.src = 'src';
             parent.document.body.append(imported);
       }, 5000);


回答4:

This might help

setTimeout(function () {
     var scriptTag = "<script>alert(1)</" + "script>";
     $("#iframe").contents().find("body").append(scriptTag);
}, 5000);