首页 > 解决方案 > 为什么我无法使用纯 JS 登录 Instagram?

问题描述

出于学习目的,我正在尝试在 Instagram 的网络版本(https://www.instagram.com/accounts/login/)上进行自动登录。

我认为只需填写用户名和密码字段,然后提交表单即可轻松完成任务;但是它不起作用,提交的表格是

这些是涉及的元素:

<input class="_2hvTZ pexuQ zyHYP" aria-label="Phone number, username, or email" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" value="">
<input class="_2hvTZ pexuQ zyHYP" aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" value="">   
<button class="sqdOP L3NKy y3zKF" disabled="" type="submit"><div class="                  Igw0E IwRSH eGOV_ _4EzTm                                                                                                              ">Log In</div></button>

所以这是我用来填充元素并提交表单的代码:

document.getElementsByName('username')[0].value = 'myusername';
document.getElementsByName('password')[0].value = 'mypassword';
document.getElementsByTagName('button')[0].removeAttribute("disabled");
document.getElementsByTagName('button')[0].click();

document.getElementsByName('username')[0].value = 'myusername';
document.getElementsByName('password')[0].value = 'mypassword';
document.getElementsByTagName('button')[0].click();
<input class="_2hvTZ pexuQ zyHYP" aria-label="Phone number, username, or email" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" value="">
<input class="_2hvTZ pexuQ zyHYP" aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" value="">
<button class="sqdOP L3NKy y3zKF" disabled="" type="submit"><div class="                  Igw0E IwRSH eGOV_ _4EzTm">Log In</div></button>

前两行将填写字段,第四行将提交表单;不知何故,这行不通。实际上,即使是填写字段的行似乎也无法正常工作,因为当我提交表单时,我可以看到没有字段被发送到服务器。

似乎问题与 React 有关,但为什么我的代码不起作用?它应该像纯 JavaScript 一样工作;我在这里想念什么?

在此处输入图像描述

标签: javascriptreactjs

解决方案


如果页面使用的是 React 16(或兼容版本),则可以针对此用例修改“什么是在 react js 中触发 onchange 事件的最佳方法”的答案:

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

modifyInput('username', 'myusername')
modifyInput('password', 'mypassword')
submit()

推荐阅读