Yves Kipondo
Yves Kipondo

Reputation: 5603

Insert string with script tag with javascript code into the DOM

I have a string which contains html script tag which contains some javascript code. I receive that code from another server via websocket.

That string contains some javascript code which performs some changes to the DOM. so I want to evaluate that string. I know that The eval() function evaluates JavaScript code represented as a string. But when I evaluate that string I'm getting some escaping error.

Is there any way to append string with javascript code into the DOM and perform the evaluation of that piece of code at the time of their insertion into the DOM.

So consider I have a variable chain like bellow

let chain = "<script>console.log('test')</script>";

I want to append that string which is a representation of a html script tag into the DOM and I want that to be evaluate at the same time it's inserted into the DOM. After that I'll expect to have some log into the browser console.

Upvotes: 1

Views: 1217

Answers (2)

phentnil
phentnil

Reputation: 2279

If you're just wanting to perform eval on the string you're receiving, you need to strip the tags and eval the new string.

The following snippet should work fine for your basic requirements. Just remember that eval is not recommended.

let chain = "<script>console.log('test')<\/script>";
let code = chain.replaceAll(/<\/?[^<>]*>/g, "");
console.log(chain, code);
eval(code);

Upvotes: 0

Alan Omar
Alan Omar

Reputation: 4217

I think this is what you are looking for.

Note: I had to change the closing tags in the string from </script> to <\/script> to make the code snippet work on SO:

let chain = "<script>console.log('Test')<\/script>";
let code = chain.replace('<script>','').replace('<\/script>','')

let script = document.createElement('script')
script.onload = eval(code)

document.body.appendChild(script);

Upvotes: 1

Related Questions