前端的“SQL注入”,处理含有html标签的字符串

前言

上个月写了一个老项目,用的语言是JQ,项目在测试的时候,遇到了测试人员的前端语言注入,在表单内容里输入了带有html标签的字符内容,导致列表崩溃。至今记忆尤深,今天看文章的时候看到了腾讯的这个方法,又重新写了一个demo。

核心方法

function htmlEncode(iStr) {
	let sStr = iStr;
	sStr = sStr.replace(/&/g, "&");
	sStr = sStr.replace(/>/g, ">");
	sStr = sStr.replace(/</g, "&lt;");
	sStr = sStr.replace(/"/g, "&quot;");
	sStr = sStr.replace(/'/g, "&#39;");
	return sStr;
}

该方法来自于腾讯的JavaScript安全指南

使用方法

const text = htmlEncode(value)

value:需要转换的字符串

Demo

效果

效果图

HTML
		<div class="content">
		
			<h3>新增表单</h3>
			<input id="a" type="text">
			<button type="submit" onclick="start()">保存</button>
			<p class="line"></p>
			
			<h3>列表</h3>
			<div id="list">
				<div class="box">
					<p>展示输入的数据</p>
				</div>
				<div class="box">
					<p>看看有没有影响</p>
				</div>
			</div>
			
			<button onclick="clearList()">清空</button>
		</div>
JS
		<script>
			function start() {
				const a = document.getElementById('a')
				const text = htmlEncode(a.value)
				const list=document.getElementById('list')
				let html=''
				html=`
					<div class="box">
						<p>展示输入的数据</p>
						<p>${text}</p>
					</div>
					<div class="box">
						<p>看看有没有影响</p>	
					</div>`
				list.innerHTML=html
			}
			
			function htmlEncode(iStr) {
				let sStr = iStr;
				sStr = sStr.replace(/&/g, "&amp;");
				sStr = sStr.replace(/>/g, "&gt;");
				sStr = sStr.replace(/</g, "&lt;");
				sStr = sStr.replace(/"/g, "&quot;");
				sStr = sStr.replace(/'/g, "&#39;");
				return sStr;
			}
			function clearList(){
				const list=document.getElementById('list')
				list.innerHTML=''
			}
		</script>
CSS
		<style>
			.content {
				width: 500px;
				margin: auto;
				border: 1px solid #ebeef5;
				box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
				text-align: center;
				border-radius: 4px;
				height: 1000px;
				overflow: auto;
			}

			input {
				border: 1px solid #ebeef5;
				padding: 7px 10px;
				border-radius: 4px;
				outline: none;
			}

			button {
				border: 1px solid #ebeef5;
				padding: 5px 10px;
				border-radius: 4px;
				margin-right: 10px;
				color: #fff;
				background-color: #409eff;
				border-color: #409eff;
			}
			.line{
				margin: 20px auto;
				border: 1px solid #ebeef5;
				box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
			}
			.list{
				text-align: center;
			}
			.box {
				width: 300px;
				height: 300px;
				box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
				text-align: center;
				line-height: 30px;
				border-radius: 4px;
				border: 1px solid #ebeef5;
				background-color: #fff;
				overflow: hidden;
				color: #303133;
				transition: .3s;
				letter-spacing: 3px;
				margin: 10px auto;
			}
		</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值