8

I've been trying to write a bot to autocomplete some forms on a website, by copy+pasting the script into the Chrome console. (Nothing illegal.) However, the problem is that this website is written in React, which means that the controlled components they use for forms interfere with simple form.value changes. If I try to fill a form using something akin to form.value = answer, I still need to do a manual keypress on the form to have it work, which isn't suited for my needs of automation.

What I have tried so far:
- Filling in the form.value and firing a keypress/keydown/keyup afterwards.
- Filling in the form.value minus one letter and firing a keypress afterwards, corresponding to the letter that was missed out.

For some strange reason afterwards, as well, the enter key doesn't work to submit until I do the manual keypress.

Can anyone help me out? Thanks!

1
  • document.execCommand with insertText parameter usually solves this. See examples and documentation.
    – woxxom
    Commented Apr 26, 2018 at 5:32

1 Answer 1

6

Better dirty way for filling form fields I use this when doing dirty browser testing of forms

Adapted from Here

Updated July 2023 to include select and checkboxes

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

Addressing the specific question

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

Or if you want to replace the text every time

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

I have a chrome script dev tools -> sources -> scripts that I use when doing dirty tests of forms

(()=>{
    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]));
}
)()
2
  • HI @styks Your code is useful, I need to achieve the same for input type="number" , input type="checkbox", and input type="dropdown" . its not working My sample code // Get a reference to the dropdown/select element const dropdown = document.getElementById('currentState'); // Select the desired option const selectedValue = 'NY'; for (let i = 0; i < dropdown.options.length; i++) { if (dropdown.options[i].value === selectedValue) { dropdown.options[i].selected = true; break; } } Commented Jul 14, 2023 at 6:09
  • 1
    @PraneshJanarthanan - I've updated the original answer to also handle select and checkbox options
    – styks
    Commented Jul 14, 2023 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.