简体   繁体   English

为什么为输入设置值在 Whatsapp 上不起作用?

[英]Why setting a value for an input won't work on Whatsapp?

My JS skills are limited and i'm starting my studies on React.我的 JS 技能有限,我开始学习 React。

I want to do a simple task: just access the web version of Whatsapp ( https://web.whatsapp.com ), and fill the input to search a contact.我想做一个简单的任务:只需访问 Whatsapp 的 web 版本( https://web.whatsapp.com ),然后填写搜索联系人。 I want to do via JS the same thing i do when i manually enter the input and type a contact name: Whatsapp will search for this contact and show the results.我想通过 JS 执行与手动输入输入并键入联系人姓名时相同的操作:Whatsapp 将搜索此联系人并显示结果。

Because the page has only one input, my first try was to simple set the value of this input:因为页面只有一个输入,我的第一次尝试是简单地设置这个输入的值:

document.getElementsByTagName('input')[0].value = 'contact name';

This will fill the input, but not trigger the event that would make Whatsapp actually search the contact;这将填充输入,但不会触发使 Whatsapp 实际搜索联系人的事件; see the image below:见下图:

在此处输入图像描述

So i tried another approach, as suggested in an answer to a similar question i made last week:所以我尝试了另一种方法,正如我上周对类似问题的回答中所建议的那样:

var setValue = Object.getOwnPropertyDescriptor(
  window.HTMLInputElement.prototype,
  "value"
).set
var modifyInput = (value) => {
  const input = document.getElementsByTagName('input')[0]
  setValue.call(input, value)
  input.dispatchEvent(new Event('input', { bubbles: true}))
}

modifyInput('contact name')

In this case, nothing happens at all, no errors but the input is not filled.在这种情况下,什么也没有发生,没有错误,但输入没有填充。

What approach should i take to achieve this task?我应该采取什么方法来完成这项任务?

At the time of writing, the page is using React, so the workaround for setting value is probably still needed.在撰写本文时,该页面正在使用 React,因此可能仍需要设置值的解决方法。 But the element also needs to gain focus before the search is active:但该元素还需要在搜索激活之前获得focus

var setValue = Object.getOwnPropertyDescriptor(
  window.HTMLInputElement.prototype,
  "value"
).set
var modifyInput = (value) => {
  const input = document.getElementsByTagName('input')[0]
  input.dispatchEvent(new Event('focus', { bubbles: true}))
  setValue.call(input, value)
  input.dispatchEvent(new Event('input', { bubbles: true}))
}

modifyInput('contact name')


For similar investigations, event listeners can be inspected in browser dev tools, eg in Firefox: 对于类似的调查,可以在浏览器开发工具中检查事件侦听器,例如在 Firefox 中:

火狐开发工具

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM