从Google Chrome控制台填写React表单

gcmastyq  于 2023-08-01  发布在  Go
关注(0)|答案(1)|浏览(120)

我一直在尝试写一个机器人来自动完成网站上的一些表格,通过复制+粘贴脚本到Chrome控制台。(没有什么是非法的。)然而,问题是这个网站是用React编写的,这意味着他们用于表单的受控组件会干扰简单的form.value更改。如果我尝试使用类似于form.value = answer的东西来填充表单,我仍然需要在表单上手动按键才能使其工作,这不适合我的自动化需求。
到目前为止我尝试过的:

  • 填充form.value,然后触发keypress/keydown/keyup。
  • 填入form.value减去一个字母,然后按下一个键,对应于遗漏的字母。
    由于一些奇怪的原因,之后,以及,回车键不工作提交,直到我做手动按键。
    有人能帮帮我吗?谢谢你,谢谢
pcww981p

pcww981p1#

填写表单字段的更好的脏方法我在对表单进行脏浏览器测试时使用这个方法

Adapted from Here

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
});

字符串

处理具体问题

document.querySelector('input').focus();
document.execCommand('insertText', false, 'Some Text For the Input');


或者如果你想每次都替换文本

document.querySelector('input').select();
document.execCommand('insertText', false, 'Some Text For the Input');


我有一个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]));
}
)()

相关问题