jquery - how to escape html to prevent XSS?

前端 未结 3 608
清酒与你
清酒与你 2021-01-15 02:35

I\'m using laravel, when a user sends a text message, it may contain some malicious code. When I use {{}} it will show me the exact text the user has sent. If h

相关标签:
3条回答
  • 2021-01-15 02:46

    We had a similar scenario in of the project I worked. We used to get html content from server side which should be appended to DOM using Jquery. Before adding it to Add, we wanted to validate the HTML content we received from Server to safe guard the XSS security issues. Following is the generic method to encode the HTML content,

    function htmlEncode(source) {
      return $("<div>").text(source).html();
    }
    
    0 讨论(0)
  • 2021-01-15 02:48

    You should use jQuery text() to encode the data.

    $('#mydata').text(data);
    

    EDIT: To create the content of #mydata you can use

    $('#mydata')
      .html("")
      .append($("<h2></h2>").text(response.name))
      .append($("<p></p>").text(response.description))
    
    0 讨论(0)
  • 2021-01-15 03:03

    you cannot render user data as HTML and escape it into safe way in the same time. You may assume that some god-level regex could help you to drop just attributes but not tags. Unfortunately there are so many ways to inject JS into markup then you will never be sure.

    So you have just few options:

    1. ignore risks at all

    2. escape all the things (either using jQuery's text() or escaping on backend side with htmlspecialchars()

    3. use non-HTML markup that is translated to HTML by simple rules in controlled way

    0 讨论(0)
提交回复
热议问题