What is XSS?
XSS attacks are also called cross-site scripting. The focus of XSS is not on cross-site, but on the execution of scripts. XSS is a computer security vulnerability that often appears in Web applications. It is caused by insufficient filtering of user input by Web applications. It allows malicious web users to insert code into pages provided to other users.
For example: write a piece of code in the database <script>alert(1)</script>
, and then the front end obtains this code through requests and other methods and renders it on the page. When the page is accessed, it will be executed, and the browser will pop up a pop-up window of 1. This is the simplest XSS attacks.
How to avoid XSS?
Front-end processing: Use character escape to escape characters such as '<', '>' <
, etc.>
Back-end processing: The same principle applies. Escape relevant characters to avoid XSS.
Character escaping (solve XSS)
Directly call the following htmlEscape('') method to filter out relevant characters that pose XSS risks:
function htmlEscape(str) { //字符转义
var escapesMap = {
'<': '<',
'>': '>',
'"': '"',
"'": '''
},
reUnescapedHtml = new RegExp(/[<>"']/g);
return (str && reUnescapedHtml.test(str)) ? str.replace(reUnescapedHtml, function(chr) {
return escapesMap[chr];
}) : (str || "");
}
character escaping
Sometimes when writing logic, you may need to reverse escape, so use the following htmlUnEscape method:
function htmlUnEscape(str) { //反转义
var unescapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
},
reEscapedHtml = new RegExp(/&(?:amp|lt|gt|quot|#39);/g);
return (str && reEscapedHtml.test(str)) ? str.replace(reEscapedHtml, function(entity) {
return unescapes[entity];
}) : (str || '')
}