Last Updated: July 21, 2019
·
7.399K
· wyuenho

Safe vs Unsafe jQuery Methods

We all know XSS is bad and we all use jQuery, unfortunately its API doc doesn't do a very good job explaining what jQuery methods are safe to use for unescaped input, and which are not.

Safe

  • .text()
  • .attr() // still needs to be careful when used in an href
  • .prop()
  • .val()

Unsafe

  • $("html code")
  • .html()
  • .append*()
  • .insert*()
  • .prepend*()
  • .wrap*()
  • .before()
  • .after()

4 Responses
Add your response

I wouldn't consider .attr as a safe method. Example: .attr('href', 'javascript:alert()')

over 1 year ago ·

Good call!

over 1 year ago ·

Superb post, thank you for this!

over 1 year ago ·

Can you please show an example of the XSS safe DOM insertion. Would it be:

jQuery('<div/>', {
    id: 'foo',
    href: 'http://google.com',
    title: 'Become a Googler',
    rel: 'external',
    text: 'Go to Google!'
}).appendTo('#mySelector');

?

Thank you

over 1 year ago ·