简体   繁体   中英

Prevent XSS in jQuery html()

I receive data from a database using ajax and then adds it together with HTML code to the website using the .html() jQuery function, like this:

$.ajax({
    url: "getDatabaseData.php",
    type: "post",
    dataType: "json",
    success: function(response){
        $("#message-div").html(getMessagesHtml(response));
    }
});

function getMessagesHtml(messages){
    var result = "";
    for(var i = 0; i < messages.length; i++){
        result += 
            "<div>" + 
                "<p>Name: " + messages[i].name + "</p>" + 
                "<p>Message: " + messages[i].message + "</p>" + 
            "</div>";
    }
    return result;
}

Here is the getDatabaseData.php that gets and returns the data from the database:

$messages = $CFG_DB->select("SELECT name, message FROM messages");
echo json_encode($messages);

Imagine for example if message contain the following text:

<script>XSS Attack code goes here</script>

My questions are:

  1. Will there be an XSS issue when doing like this?
  2. In case there is an issue, how can I prevent it?

I guess that using text() instead of html() is not an option in this case since I also add html code.

Without javascript, when printing the data using PHP I just use htmlentities on the variables received from the database to prevent XSS, for example htmlentities(messages[i].name) and htmlentities(messages[i].message). But I have not seen any similar for javascript.

Setting text with user input is the safest way. Instead of creating html strings, create elements instead

Something like:

function getMessagesHtml(messages){

  return messages.map(function(o){
    var $div = $('<div>');
    $div.append($('<p>', {text: "Name: " + o.name}));
    $div.append($('<p>', {text: "Message: " + o.message}));
    return $div;
  });

}

Per comments an alternative is create a sanitizing helper function that creates an element that passes the input string as text to the element and returns that text

function text(str){
   return $('<div>',{text:str}).text();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM