Interacting with ReactJS forms as an outsider

Recently I was attempting to automate data entry on a site that was powered by ReactJS. We’re definitely in a new world of tools that the kids are using these days – you can’t just plug data into an input box and submit a form like olden times when they use these Javascript frameworks.

ReactJS uses a “Shadow DOM” behind the scenes, and any changes you make to the traditional HTML DOM will not change those values. I initially thought my cause was dismal. But then a colleague pointed out that tools like 1Password are somehow able to fill values into those boxes and make them stick. I then went down a Javascript Event rabbit hole and figured out how to change values for inputs and select dropdowns as though I were a real user interacting with these elements.

The site also wasn’t using jQuery, so I had to go pure Javascript on it.

For input controls
To begin interacting with a text input, first select the element:

box = document.querySelector('#thebox');

Fire a focus event:

var event = document.createEvent('FocusEvent');
event.initEvent('focus', true, true);

Then iterate over each character you want to type and fire a “textInput” event. In this case, the character is “3”:

var event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, window, "3");

Be sure to blur afterward, just in case any UI updates depend on you being done with that box:

var event = document.createEvent('FocusEvent');
event.initEvent('blur', true, true);

For select dropdowns
Set the input of the control as normal, but then follow it up with an “input” and a “change” event.

select = document.querySelector('#theselect');

select.value = "the option value";

var event = document.createEvent('Event');
event.initEvent('input', true, true);

var event = document.createEvent('Event');
event.initEvent('change', true, true);

For buttons and radio controls, a click is still a click, so any of those can be interacted with traditionally.

Posted in Javascript, ReactJS

Leave a Reply

Your email address will not be published. Required fields are marked *