今天接到一个需求,要求对项目中所有的input文本框增加敏感词过滤功能。
项目框架用的是angular8,其实思路还是比较容易想到的:
可以在index.html文件中增加全局input事件监听,加载敏感词接口进行过滤,最后修改e.target.value的值即可。
不过需要注意的是,ngModel的值(vue就是v-model)不会随着e.target.value修改而修改,我们需要用e.target.dispatchEvent(new Event('input'))来强制修改之。
index.html增加如下js代码:
<script>
//================================过滤敏感词===================================================//
document.addEventListener('input', debounce(handleWords,800));
function handleWords(e) {
console.log(e.target.value);
let words = e.target.value;
fetch(`/checkSensitiveWords`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `words=${words}`
}).then(response => response.text()).then(res => {
e.target.value = res;
e.target.dispatchEvent(new Event('input'));//更新ngModel视图
})
};
function debounce(fn, delay) {
var timer = null;
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
</script>
后台用的nestjs写的:
@ApiOperation({ summary: "过滤敏感词", description: "过滤敏感关键词和特殊字符" })
@Post('checkSensitiveWords')
async checkSensitiveWords(@Body() params): Promise<any> {
let words = params.words;
let newWords = words;
console.log('words>>>', words);
if (words) {
let sensitiveWords = sensitiveWordsFunc();
if (Array.isArray(sensitiveWords)) {
sensitiveWords.forEach(item => {
let stripSpecWords = words.replace(/\s+/g, "");//获取字符串信息,清除所有空格
stripSpecWords = stripSpecWords.replace(/[\-\_\,\!\|\~\`\(\)\#\$\%\^\&\*\{\}\:\;\"\L\<\>\?]/g, '');
if (item && stripSpecWords.indexOf(item) !== -1) {
newWords = stripSpecWords.replace(item, '囗'.repeat(item.length));
}
});
console.log('newords>>>', newWords);
return newWords;
}
}
return newWords;
}