简体   繁体   中英

How to append a raw JavaScript tag to document.body without jQuery

I get a raw JavaScript tag from the server:

"<script>alert('hi');</script>"

Now, I need to append it to <body> so that it fires. I can't simply create a new script element, because this string already contains the <script> part. Is there something analogous to

child = document.createElementFromHTML("<script>alert('hi');</script>");
document.body.appendChild(child)

Thanks for any help.

EDIT

Here's why it's not a duplicate, hall monitors:

If you set the inner html of a div to be a script it won't fire. I need to append an element generated from only text to the body.

EDIT 2

final solution:

window.onload = function() {
document.body.innerHTML += "<script>alert('hi');</script>";
var script = document.scripts[document.scripts.length - 1];
var s = document.createElement("script");
s.textContent = script.textContent;
document.body.removeChild(script);
document.body.appendChild(s);
}

You can concatenate document.body.innerHTML with <script> html string, get .textContent of last script in document , create script element, set script element .textContent to value retrieved from concatenated html <script> string, remove last <script> , append new <script> to document.body .

 <script> document.body.innerHTML += "<script>alert('hi');<\\/script>"); var script = document.scripts[document.scripts.length - 1]; var s = document.createElement("script"); s.textContent = script.textContent; document.body.removeChild(script); document.body.appendChild(s); </script> 

In this way you can insert <script> tag in your HTML

 var script = document.body.appendChild(document.createElement('script')); script.text = 'alert("Hi!");' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM