Problem assigning HTML with .text () and .html ()

-1

I need to insert the HTML that refers to a hyperlinked image received through an ajax function on the page, however for security reasons I can not simply insert directly, so I'm passing this HTML code through .text () for a created div, and only after I assign this variable to .html (), however what is happening is that only the created div is recognized as HTML, the rest is displayed in plain text. How do I get everything recognized as HTML when inserting into my page while maintaining insertion security?

function start(){
    timer = setInterval( function(){
        var banner = $('<div>').text(banner()); // <a href="http://exemple.com/"><img src="imagem.jpg"/></a>
        $('#parceiros').html(banner);
    }, 3000);
}
    
asked by anonymous 31.05.2014 / 16:50

4 answers

0

I confess that I had to read it a few times to try to understand what you have in mind, and from what I was able to abstract you should use jQuery. html () instead of jQuery.text () , for value evaluation as HTML.

This makes a lot of sense simply by considering the API naming: jQuery.html () takes HTML into consideration. jQuery.text () , not.

Demo in Fiddle

However, your security may be false, depending on how server-side programming was done. My suggestion is that you only work with pure text traffic by JSON, who knows.

So you guarantee that there will be "none" (yes, quotation marks, you never know ...) possibility of malicious code injection because you will add the HTML according to the need of the GUI instead of blindly trusting an HTML that can to be breached between the interceptable stages of a Request.

    
31.05.2014 / 17:05
12

Placing to run already gives to see. The first one becomes an HTML and will be interpreted by the browser in this way, the second is a text like any other and will be printed on the page the way it is written, there will be no rendering creating a link as expected .

<html>
<head>
  <title>HTML vs Text</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scripttype="text/javascript">
    $(function(){
      $("#div1").html('<a href="example.html">Link</a><b>hello</b>');
      $("#div2").text('<a href="example.html">Link</a><b>hello</b>');
    });
  </script>
</head>
<body>
  <div id="div1"></div>
  <div id="div2"></div>
</body>
</html>
    
11.10.2018 / 16:28
5

.html() treats the string as HTML.

.text() treats the string as text.

    
11.10.2018 / 16:26
4

The .text() method works anyway, rips out any HTML content and handles text only. I do not quite understand your restrictions, but you need to use .html() instead of .text() :

function start(){
    timer = setInterval( function(){
        var banner = $('<div>').html(banner()); // <a href="http://exemple.com/"><img src="imagem.jpg"/></a>
        $('#parceiros').html(banner);
    }, 3000);
}
    
31.05.2014 / 17:02