Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda