Thursday, April 28, 2011

JQuery Escaping HTML for Preview

I am making a very simple preview window in JQuery using just an ordered list. I am worried the user will type in < or > and accidentally mess up the code for the page or do some sort of XSS. How can I encode special chars using Javascript to handle this situation?

From stackoverflow
  • if you use

    $(yourselector).text("<h1>Your text String</h1>");
    

    then jQuery will display the actual text including the special chars. If you use

    $(yourselector).html("<h1>Your text String</h1>");
    

    then the HTML special chars will be interpreted when displayed.

    I assume here that you want to display the text that your user enters between the list tags.

    Joe Philllips : In my case I'm making a list so I currently have something like this: $(selector).html('
  • ' + $(this).val() + '
  • ') -- how would I convert this to your method?
Vincent Ramdhanie : $(Your UL selector).append('
  • '); adds the li to the list and $("#someid").text($(this).val()); will then add the text to the new li. You will need to use a variable as the li's id.
    Joe Philllips : $(ul selector).append('
  • ').text(...) -- would this work instead or does append() return the parent instead of the created element?
  • Vincent Ramdhanie : append() returns the parent so as far as I can tell you need use the two statements. I don't know if anyone else could suggest a way to do it all in one statement.
  • You could also .wrap the element in a <pre> tag.

    $("#selector").wrap("<pre></pre>");
    
    tester : This might not the best idea for XSS prevention though, now that I think about it. Someone could start the input off with and end it with
     then inject whatever code they wanted in the center. Converting to .text() is more than likely the best solution.
                                        
  • If you want to store the escaped value in a variable, rather than rendering it to the page, you could also try:

    $('<div></div>').text(str).html()
    
  • 0 comments:

    Post a Comment