Nat TaylorBlog, Product Management & Tinkering

UserScripts and ReactJS Forms

Published on . Updated 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) {, value);
  } else {, value);

window.addEventListener('load', function() {
  let username = document.querySelector('input[type=text]');
  setNativeValue(username, 'admin');
  username.dispatchEvent(new Event('input', { bubbles: true }));

Popular Posts

Post Navigation