How To Prevent Cross-Site Scripting (XSS) in JavaScript
How To Prevent Cross-Site Scripting (XSS) in JavaScript
https://www.example.com/search?q=<search_term>
We use cookies to personalize content and
ads, to provide social media features and to
analyze our traffic. Some of these When
cookiesa user enters a search term and submits the form, the
also help improve your user experience
searchon term is included in the URL as a parameter. The server
our websites, assist with navigation and your
then processes the search request and returns the search
ability to provide feedback, and assist with ACCEPT COOKIES COOKIES SETTINGS
results in the response.
our promotional and marketing efforts.
Please read our Cookie Policy for a more
detailed description and click on the settings
Now, imagine an attacker creates a malicious link that includes a
button to customize how the site uses
script tag in the search term parameter:
cookies for you.
https://www.example.com/search?q=<script>alert('XSS attack!')</script>
function search() {
var query = document.getElementById("searchBox").value;
var resultsDiv=cument.getElementById("results");
resultsDiv.innerHTML = "Search results for:" + query;
}
The vulnerability here is that the search term entered by the user
is directly added to the DOM using the innerHTML property,
without being properly sanitized or encoded.
If the user enters this search term and clicks the search button,
the attacker’s code will be executed by the victim’s browser,
displaying an alert box with the message “DOM-based XSS
attack!”
function escapeHTML(str) {
return str.replace(/[&<>"'\/]/g, function (char) (
switch (char) {
case '&':
return '&';
case '<':
return '<';
case '>':
return '>';
case '"':
return '"';
case '\':
return ''';
case '/':
return '/';
default:
return char;
}
});
}
This header specifies that only content from the same origin as
the page is allowed to be loaded.
This function creates a new div element and sets its inner text to
the user input. The inner HTML of the div element is then
returned, which contains the encoded input.
Conclusion
RELATED POSTS
PRODUCTIVITY DEBUGGING
WEB
WEB ANGULAR
TOPICS
Web
Mobile
Desktop
Design
Productivity
People
Release
search blogs...
Subscribe
Copyright © 2024 Progress Software Corporation and/or its subsidiaries or affiliates. All
Rights Reserved.
Progress, Telerik, Ipswitch, Chef, Kemp, Flowmon, MarkLogic, Semaphore and certain product
names used herein are trademarks or registered trademarks of Progress Software
Corporation and/or one of its subsidiaries or affiliates in the U.S. and/or other countries. See
Trademarks for appropriate markings.