How do you prevent XSS (cross-site scripting) when using jQuery?
<div id="out"></div>
var userInput = '<img src=x onerror=alert(1)>';
$('#out').text(userInput);
console.log($('#out').html());
console.log($('#out').find('img').length);
Console output
<img src=x onerror=alert(1)>
0
- Use
.text()or.val()for user data..html(),.append(string)and$(string)read HTML. - Create elements with
$('<li>').text(data). - Validate and escape on the server, and use a Content Security Policy.
Learn more about the similar topics:
| Tutorials |
|---|
| jQuery Introduction |
| jQuery Get Started |
| jQuery Syntax |
| jQuery Document Ready Function |
| jQuery noConflict() Method |
| jQuery vs Vanilla JavaScript |
| jQuery 4 and Upgrading from jQuery 3 |
| Exercises & Assignments |
|---|
| No Content Found. |