简体   繁体   中英

How to insert html as text using .html() in javascript?

In my javascript app, I insert a user message using the code:

var displayMessages = function(response, onBottom) {
    var user = GLOBAL_DATA.user;

    var acc = '';
    for(var i=0; i<response.length; i+=1) {
        var obj = response[i];

        var acc_temp = "";
        acc_temp += '<div class="message ' + (obj['user_id']==user['id'] ? 'message-right' : 'message-left') + '">';
        acc_temp += '<div>' + Autolinker.link($(obj['message']).text()) + '</div>';
        if (obj['user_id']!=user['id']) {
            acc_temp += '<div class="message-details">' + obj['first_name'] + ' ' + obj['last_name'] + '</div>';
        }
        acc_temp += '<div class="message-details">' + obj['date_sent'] + '</div>';
        acc_temp += '</div>';

        acc = acc_temp + acc;
    }

    addMessage(acc, onBottom);
};

The problem is that, if obj['message'] = "<script>alert(1);</script>"; then what gets printed on the screen is "alert(1);" because I use .text() . How can I insert the string with the script tags, so that it looks exactly like that on the page? I don't want it to get executed.

Thanks

I use these helper functions.

function htmlEncode(value){
  return $('<div/>').text(value).html();
}
function htmlDecode(value){
  return $('<div/>').html(value).text();
}

I would escape the other variables as well if you are not sure that they will not have any executable code.

I solved it using this:

function escapeHTML(str) {
    return $("<p></p>").text(str).html();
}

I think you'll need to wrap your object in a dummy tag, then you can retrieve the full html from that.

You'll have issues though, because you're using a script tag, which will be evaluated.

obj['message'] = "<script>alert(1);</script>";
>
$(obj['message']).text();
> "alert(1);"
$(obj['message']).html();
> "alert(1);"
$(obj['message']).wrapAll('<div>').text();
// alerts with 1
> "alert(1);"

Not using a script tag will work.

obj['message'] = "<span>alert(1);</span>";
>
$(obj['message']).wrapAll('<div>').text();
> "<span>alert(1);</span>"

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