vir*_*u13 7 javascript google-chrome google-chrome-devtools reactjs
我一直在尝试编写一个机器人,通过将脚本复制+粘贴到 Chrome 控制台中来自动完成网站上的某些表单。(没有什么非法的。)但是,问题是这个网站是用 React 编写的,这意味着他们用于表单的受控组件会干扰简单的form.value更改。如果我尝试使用类似于 的内容填写表单form.value = answer,我仍然需要在表单上手动按键才能使其工作,这不适合我的自动化需求。
到目前为止我已经尝试过:
- 填写form.value并随后触发按键/按键/按键。
- 填写form.value减去一个字母,然后按下一个按键,对应于遗漏的字母。
之后,由于一些奇怪的原因,在我手动按键之前,回车键无法提交。
谁能帮我吗?谢谢!
填写表单字段的更好的脏方法 我在对表单进行脏浏览器测试时使用此方法
2023 年 7 月更新以包含选择和复选框
const setFormFields = (formFields) => {
const inputTypes = [
window.HTMLInputElement,
window.HTMLSelectElement,
window.HTMLTextAreaElement
];
const triggerInputChange = (selector, value) => {
const node = document.querySelector(selector);
// only process the change on elements we know have a value setter in their constructor
if (inputTypes.indexOf(node.__proto__.constructor) > -1) {
const setValue = Object.getOwnPropertyDescriptor(node.__proto__, 'value').set;
let event = new Event('input', {
bubbles: true
});
if(node.__proto__.constructor === window.HTMLSelectElement){
event = new Event('change', {
bubbles: true
});
} else if (node.type === 'checkbox') {
node.checked = value;
event = new Event('change', {
bubbles: true
});
}
setValue.call(node, value);
node.dispatchEvent(event);
}
}
Object.entries(formFields).forEach(([selector, value]) => triggerInputChange(selector, value));
}
// Usage:
setFormFields({
'.substrate': '20',
'name="first_name"': 'McFirsty',
'name="last_name"': 'McLasty',
'name="accept_terms"': true, // for checkboxes, use true for checked and false for unchecked
'name="state"': 'VA' // for select boxes, use the value of the option you want to select
});
Run Code Online (Sandbox Code Playgroud)
解决具体问题
document.querySelector('input').focus();
document.execCommand('insertText', false, 'Some Text For the Input');
Run Code Online (Sandbox Code Playgroud)
或者如果您想每次都替换文本
document.querySelector('input').select();
document.execCommand('insertText', false, 'Some Text For the Input');
Run Code Online (Sandbox Code Playgroud)
我有一个 chrome 脚本dev tools -> sources -> scripts,在对表单进行脏测试时使用它
(()=>{
const fillText = (selector, value) => {
document.querySelector(selector).select();
document.execCommand('insertText', false, value);
}
const formFields = [
['[data-ref-name="company"]', 'My Company'],
['[data-ref-name="first_name"]', 'Styks']
]
formFields.forEach(field => fillText(field[0], field[1]));
}
)()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4395 次 |
| 最近记录: |