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

254
Visualizações
Javascript/Html: appending to section as text not html code

I have a web app for chatting and when someone would send something it'd send the message to everyone by appending that text to the chat section element but if they typed code in there it would output the code and run it which is a problem as that is dangerous which I want to fix but not sure how to.

socket.on('message', function (data) {
  $('.chat').append('<p><strong style=color:'+data.color+'> ' + data.user + '</strong> <span style=color:"black">' + data.message + '</span></p>');
});
<div id="maindiv1"> 
  <section id="chatSection" class="chat"></section>
</div>

So if I put:

<h1> hello </h1>

It would make that element for all users in chat or like location.assign("https://google.com") would make it go to google for all users which I don't want i'd want it to send whatever as text not code but still be able to have the functionality of adding stuff like

<p><strong style=color:'+data.color+'> ' + data.user + '</strong> <span style=color:"black">' + data.message + '</span></p>

...for only when its sent and not the message which is data.message.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Just encode the text message before. Try this:

socket.on('message', function (data) {

var securedText = $('<div/>').text(data.message).html();
  $('.chat').append('<p><strong style=color:'+data.color+'> ' + data.user + '</strong> <span style=color:"black">' + securedText + '</span></p>');
});
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