在rasa-webchat中集成脏话拦截JS时addEventListener调用失败如何解决?
报错原因
该报错是因为执行事件绑定代码时,rasa-webchat的输入框还没有被渲染到页面DOM中:
- rasa-webchat是异步加载的组件,你直接在全局script末尾执行绑定逻辑时,webchat还未完成加载和渲染,
document.getElementsByName('message')[0]返回的是undefined,调用addEventListener自然报错 - 在浏览器控制台运行代码时,页面已经加载完成,输入框已存在,所以功能可以正常生效
修复后的完整代码
将事件绑定逻辑移到rasa-webchat的加载完成回调中,同时增加DOM检测逻辑,确认输入框渲染完成后再绑定事件:
<html> <body> <style> /* custom styling */ </style> <script>!(function () { let e = document.createElement("script"), t = document.head || document.getElementsByTagName("head")[0]; e.src = "https://cdn.jsdelivr.net/npm/rasa-webchat@1.0.1/lib/index.js"; e.async = !0; e.onload = () => { window.WebChat.default( { initPayload: '/greet', customData: { language: "en" }, socketUrl: "http://localhost:5005", title: 'X', subtitle: 'Say hi to get started', profileAvatar: './images/logo_white.jpg', showFullScreenButton: true, params: {storage: "session",}, displayUnreadCount: true, showMessageDate: true, }, null ); // 脏话拦截逻辑 function blockProfanity(){ const input = document.getElementsByName('message')[0]; if(!input) return; console.log(input.value); if (input.value.includes('fuck') || input.value.includes('Please refrain from using Profanity')){ input.value = 'Please refrain from using Profanity'; input.style.color = 'red'; input.style.fontWeight = 900; } else{ input.style.color = 'black'; input.style.fontWeight = 200; } } // 轮询检测输入框是否渲染完成 function checkInputExist() { const input = document.getElementsByName('message')[0]; if(input) { input.addEventListener('keyup', blockProfanity); alert("document loaded!"); } else { setTimeout(checkInputExist, 100); } } checkInputExist(); }; t.insertBefore(e, t.firstChild); })(); console.log('Done'); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Faraz Ali Khan
相关产品推荐
相关产品推荐

