Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!