1

Weeding out a few issues with my site when I found this curious issue.

<img src=".." width="1200" height="1200" alt="&lt;script&gt;alert(&quot;foo&quot;);&lt;/script&gt;" />

The CMS appears to have done it's jobs and converted <script>alert('foo')</script> into what you see above. I display the caption with the following code.

site.caption = {

    container : $('#caption'),

    set : function(str) {

        if (str && str.length) {
            this.container.html('<span>'+str+'</span>').show(); console.log(str);
        } else {
            this.container.hide();
        }

    }

};

The function is called like this.

site.caption.set($(nextSlideElement).find('img').attr('alt'));

When this line runs an alert box pop's up with the text 'foo'. When I do the following in the site.caption.set function it shows the valid html.

console.log(str);

I am using jQuery 1.8.3. Does anyone know why this is happening? How do I show the text <script>alert('foo')</script> without it being run?

2 Answers 2

3

jQuery isn't converting it, the browser is when it parses the HTML.

If you want to treat a string as text instead of HTML, then use jQuery('foo').text(value) instead of jQuery('foo').html(value).

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

Comments

1
this.container.html('<span>'+str+'</span>')

Never concatenate HTML strings. Let jQuery do it for you. Get into this habit and you won't run into this problem.

this.container.empty().append($('<span/>').text(str));

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.