Front-end js implements character escaping and anti-escaping

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 '<', '>' &lt;, etc.&gt;

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 = {
			'<': '&lt;',
			'>': '&gt;',
			'"': '&quot;',
			"'": '&#039;'
		},
		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 = {
			'&amp;': '&',
			'&lt;': '<',
			'&gt;': '>',
			'&quot;': '"',
			'&#39;': "'"
		},
		reEscapedHtml = new RegExp(/&(?:amp|lt|gt|quot|#39);/g);
	return (str && reEscapedHtml.test(str)) ? str.replace(reEscapedHtml, function(entity) {
		return unescapes[entity];
	}) : (str || '')
}

If it is helpful, you can like + collect + follow, and I will share more knowledge with you in the future! ! !

Welcome to join the QQ technology group: 568984539. When joining the group, please note 'region-name-technology type' to prevent random additions.

Regarding this article, if you have any questions, you can leave a message in the comment area and I will reply as soon as I see it.

Guess you like

Origin blog.csdn.net/qq_42961150/article/details/125747227
Recommended