UserScripts and ReactJS Forms
Published on .
Recently I need to auto-fill a form with a UserScript in a React application. I discovered that $("input").value="foo"
didn’t play nice with React (which I guess makes sense because of state management …I guess) so here’s the alternative I came up with:
function setNativeValue(element, value) {
const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
const prototype = Object.getPrototypeOf(element);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(element, value);
} else {
valueSetter.call(element, value);
}
}
window.addEventListener('load', function() {
let username = document.querySelector('input[type=text]');
setNativeValue(username, 'admin');
username.dispatchEvent(new Event('input', { bubbles: true }));
})