WhatsApp Web自动化:JS输入号码后无法触发搜索结果加载
WhatsApp Web自动化:JS输入号码后无法触发搜索结果加载
我之前也碰到过这个问题!WhatsApp Web的前端对输入事件的监听做得相当严格,单纯触发input事件往往不够——它的搜索逻辑可能依赖更完整的真实输入事件链(比如键盘按下/松开、原生文本插入事件),而你之前的代码只触发了单个input事件,没覆盖到WhatsApp内部监听的所有触发点。
解决方法:模拟完整的输入事件链
下面提供两种经过验证的有效方案,你可以任选一种尝试:
方案一:手动触发多组关键事件
直接修改输入框值后,补充触发keyup、change等WhatsApp可能监听的事件,完整模拟输入后的事件流:
const number = "xxxxxx"; // 替换为你的目标号码 const newChatButton = document.querySelector('[data-icon="new-chat-outline"]'); newChatButton?.click(); const interval = setInterval(() => { const SEARCH_INPUT = document.querySelector('[aria-label="Search name or number"]'); if (SEARCH_INPUT) { // 重置输入框并聚焦 SEARCH_INPUT.value = ''; SEARCH_INPUT.focus(); // 设置目标号码 SEARCH_INPUT.value = number; // 触发input事件通知内容变更 SEARCH_INPUT.dispatchEvent(new Event('input', { bubbles: true, cancelable: true })); // 触发keyup事件模拟手动输入后的按键松开 SEARCH_INPUT.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, cancelable: true, key: number.slice(-1) // 用号码最后一位作为模拟按键,更贴近真实输入 })); // 额外触发change事件覆盖所有可能的监听 SEARCH_INPUT.dispatchEvent(new Event('change', { bubbles: true, cancelable: true })); clearInterval(interval); } }, 500);
方案二:使用原生文本插入命令(更推荐)
利用浏览器的document.execCommand('insertText')方法,完全模拟真实的手动文本插入,这个方法会自动触发所有原生输入事件,对大多数严格监听的网站都有效:
const number = "xxxxxx"; // 替换为你的目标号码 const newChatButton = document.querySelector('[data-icon="new-chat-outline"]'); newChatButton?.click(); const interval = setInterval(() => { const SEARCH_INPUT = document.querySelector('[aria-label="Search name or number"]'); if (SEARCH_INPUT) { SEARCH_INPUT.focus(); // 先清空输入框(防止残留内容干扰) document.execCommand('selectAll', false, null); document.execCommand('delete', false, null); // 插入目标号码,自动触发所有原生输入事件 document.execCommand('insertText', false, number); // 额外触发一次keyup确保WhatsApp捕捉到事件 SEARCH_INPUT.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, key: 'Tab' })); clearInterval(interval); } }, 500);
为什么之前的代码无效?
WhatsApp Web的搜索逻辑并没有只监听input事件,它可能还依赖keyup或其他键盘事件来触发搜索。手动输入时,每个字符都会触发keydown→input→keyup的完整链,而你之前的代码只触发了input事件,缺少了WhatsApp内部需要的触发信号,导致它没有执行搜索逻辑。
备注:内容来源于stack exchange,提问作者user23886518
相关产品推荐
相关产品推荐

