0

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

1
  • 3
    str replace > -> &gt; and < -> &lt;. e.g. html-encode the html metachars. Commented Mar 10, 2015 at 21:32

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

I solved it using this:

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

Comments

0

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>"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.