Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

89
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda