我需要防止在输入字段中添加脚本。有什么方法可以防止在文本字段/文本区域中添加 javascript 代码吗?
function filter($event) {
var regex = /[^a-zA-Z0-9_]/;
let match = regex.exec($event.target.value);
console.log(match);
if (match) {
$event.preventDefault();
} else {
return true;
}
}
您可以通过定义
blacklist
正则表达式来清理输入,该正则表达式包含输入不允许的模式,然后如果与黑名单正则表达式匹配,则用空字符串替换输入字符串的部分。
现在我只是添加了一个简单的黑名单正则表达式(您可以根据您的要求修改它),它将替换
<
和 >
之间的所有文本。例如:如果用户输入 <script>Hello</script>
(整个输入文本将被 keyup 事件中的空字符串替换。
const blackList = /<+>/ig
function sanitizeInput() {
const inputStr = document.getElementById('inputStr').value;
console.log('inputStr', inputStr)
document.getElementById('result').innerHTML = inputStr?.replace(blackList, '')
}
<input type="text" id="inputStr" onkeyup="sanitizeInput()"/>
<div id="result"></div>
在这里我找到了解决方案,我认为它会起作用。
input.replace(//g, ">").replace(/=/g, "等于;");
使用
xss
包效果很好(https://github.com/leizongmin/js-xss)
在nodeJs上:
var xss = require("xss");
var html = xss('<script>alert("xss");</script>');
console.log(html);