javascript - 以编程方式填写 reactjs 表单

标签 javascript reactjs greasemonkey userscripts

我正在编写一个用户脚本,但无法填写由 reactjs 制作的表格。我的代码:

document.querySelector("#id-username").value = "name@domain.xx";
// Attempt to notify framework using input event
document.querySelector("#id-username").dispatchEvent(new Event("input", {data:"name@domain.xx"}));
// Attempt to notify framework using change event
document.querySelector("#id-username").dispatchEvent(new Event("change"));
// This doesn't help either
document.querySelector("#id-username").dispatchEvent(new Event("blur"));
// Submit the form using button (it's AJAX form)
document.querySelector("fieldset div.wrap button").click();

加载页面后,我将此代码输入到开发者工具控制台。但是,该表单忽略了我的编程输入:

image description

可以找到表格here .我工作的目的是自动登录给定的网站。我提供了具体的 URL,但我希望可以应用于任何 reactjs 表单的通用解决方案(例如,使用一些 reactjs API)。其他用户可能需要此解决方案来为其网站编写自动化测试。

最佳答案

对于 Chrome 版本 64,有一个解决方法。否则事件将被忽略。

参见:https://github.com/facebook/react/issues/10135#issuecomment-314441175

(全部归功于链接中的 fatfisz)

代码

function setNativeValue(element, value) {
  const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
  const prototype = Object.getPrototypeOf(element);
  const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;

  if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(element, value);
  } else {
    valueSetter.call(element, value);
  }
}

用法

setNativeValue(textarea, 'some text');
// you must dispatch the input event, or the value will not update !!!
textarea.dispatchEvent(new Event('input', { bubbles: true }));

关于javascript - 以编程方式填写 reactjs 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42795059/

相关文章:

javascript - 使用 JavaScript 选中复选框时更改样式

javascript - Express js 从 URL 的根部获取参数(不像 req.params 那样简单)

javascript - React 组件未接收 Redux 存储更新的 props

javascript - 如何在 chart.js 中的图例项上显示工具提示

javascript - Greasemonkey 的简单替代品

javascript - REGEX 用于获取 URL 末尾不带/的 ID

javascript - 如何使用 JSON Map 响应通过 Angular ng-repeat 生成表

javascript - 如何使用 call/apply 检查函数是否被调用

reactjs - 使用 create-react-app 的多个入口点

javascript - 从 Greasemonkey 访问变量到页面,反之亦然