I am writing an userscript and I can't manage to fill a form made by reactjs. My code:
document.querySelector("#id-username").value = "[email protected]";
// Attempt to notify framework using input event
document.querySelector("#id-username").dispatchEvent(new Event("input", {data:"[email protected]"}));
// Attempt to notify framework using change event
document.querySelector("#id-username").dispatchEvent(new Event("change"));
// This doesn't help either
document.querySelector("#id-username").dispatchEvent(new Event("blur"));
// Submit the form using button (it's AJAX form)
document.querySelector("fieldset div.wrap button").click();
I entered this code into developper tools console after loading the page. However the form ignores my programatical input:
The form can be found here. The purpose of my work is to automate login to given website. I provided the specific URL, but I expect generic solution to this problem (eg. using some reactjs API) that can be applied to any reactjs form. Other users might need this solution for writing automated tests for their sites.
Event must be emmited to ReactJS to make it register the value. In particular, the input
event. It is really important to ensure that the event bubbles - React JS has only one listener at the document
level, rather than on the input field. I crafted the following method to set the value for input field element:
function reactJSSetValue(elm, value) {
elm.value = value;
elm.defaultValue = value;
elm.dispatchEvent(new Event("input", {bubbles: true, target: elm, data: value}));
}