Skip to content

Latest commit

 

History

History
56 lines (40 loc) · 2.07 KB

how-can-i-prevent-jquery-xss-vulnerabilities.md

File metadata and controls

56 lines (40 loc) · 2.07 KB

How can I prevent jQuery XSS vulnerabilities?

// plain

  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

onelinerhub: How can I prevent jQuery XSS vulnerabilities?