user1130176
user1130176

Reputation: 1878

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);
}

Upvotes: 2

Views: 3452

Answers (2)

guest271314
guest271314

Reputation: 1

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>

Upvotes: 4

neophyte
neophyte

Reputation: 6626

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

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

Upvotes: 1

Related Questions