【问题标题】:Filling a react form from the Google Chrome console从 Google Chrome 控制台填写反应表单
【发布时间】:2018-10-06 16:49:25
【问题描述】:

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

到目前为止我已经尝试过:
- 填写form.value,然后触发按键/keydown/keyup。
- 填写form.value 减去一个字母,然后按下按键,对应于错过的字母。

由于某些奇怪的原因,在我手动按键之前,回车键也无法提交。

谁能帮帮我?谢谢!

【问题讨论】:

  • document.execCommand 和 insertText 参数通常可以解决这个问题。查看示例和文档。

标签: javascript reactjs google-chrome google-chrome-devtools


【解决方案1】:

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

Adapted from Here

(()=>{
    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
                });
            }
            setValue.call(node, value);
            node.dispatchEvent(event);
        }
    }

    const formFields = [
        ['company', 'Shorts & Company'],
        ['first_name', 'McFirsty'],
        ['last_name', 'McLasty'],
        ['address1', '123 N. In The Woods'],
        ['city', 'Trunkborns'],
        ['state', 'WA'],
        ['zip', '55555']
    ];

    formFields.forEach(field=>triggerInputChange(field[0], field[1]));
}
)()

解决具体问题

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多