9951 explained code solutions for 126 technologies


jqueryHow can I prevent jQuery XSS vulnerabilities?


  1. Use the jQuery .html() or .text() method to sanitize user input. This will ensure that any malicious code is removed before it is rendered in the browser.
var userInput = '<script>alert("XSS attack!")</script>';
$('#userInput').html(userInput);
  1. Use the jQuery .attr() method to set attributes on elements. This will ensure that any malicious code is removed before it is rendered in the browser.
var userInput = '<script>alert("XSS attack!")</script>';
$('#userInput').attr('title', userInput);
  1. Use the jQuery .data() method to set data attributes on elements. This will ensure that any malicious code is removed before it is rendered in the browser.
var userInput = '<script>alert("XSS attack!")</script>';
$('#userInput').data('userInput', userInput);
  1. Use the jQuery .removeData() method to remove data attributes from elements. This will ensure that any malicious code is removed before it is rendered in the browser.
$('#userInput').removeData('userInput');
  1. Use the jQuery .replaceWith() method to replace elements with sanitized content. This will ensure that any malicious code is removed before it is rendered in the browser.
var userInput = '<script>alert("XSS attack!")</script>';
$('#userInput').replaceWith('<div>' + userInput + '</div>');
  1. Use the jQuery .on() method to bind events to elements. This will ensure that any malicious code is not executed when the event is triggered.
$('#userInput').on('click', function(){
    alert('XSS prevented!');
});
  1. Use the jQuery .off() method to unbind events from elements. This will ensure that any malicious code is not executed when the event is triggered.
$('#userInput').off('click');

Helpful links

Edit this code on GitHub