17

I am building a tiny Chrome Extension for my own personal use.

In Facebook's ads manager(Uses React) i want to change a textarea field's value to a value generated by my chrome extension.

i tried it doing the old fashion way like this

document.querySelector('textarea').value = myValue;

this changes the value on screen but in chrome's inspect element the value doesn't change and when i focus on the input element value resets.

Here is the picture of how react component looks like:

1]

Here is the picture of this react components props & states:

2]

In above component i want to change the state.displayValue to my value.

how it can be done?

Badal
  • 3,738
  • 4
  • 33
  • 60

2 Answers2

12

As mentioned previously, you need to notify react about your manual changes. However, with React 16 this is not so straightforward.

const element = document.querySelector('textarea')
const event = new Event('input', { bubbles: true })
const previousValue = element.value

element.value = 'next value'
element._valueTracker.setValue(previousValue)
element.dispatchEvent(event)

Here is a working codesandbox with source code.
To see demo only you can open this link and call window.triggerChange('new value') function directly from browser dev tools console.

You'll see React's onChange and then setState events being triggered!

amankkg
  • 4,503
  • 1
  • 19
  • 30
  • I just tried this on the email field, document.querySelector('[type=email]') on this React page: http://seatgeek.com/cowboys/ and nothing happened – Aymon Fournier Aug 01 '18 at 20:49
  • @AymonFournier hmm, I tried with this selector `document.querySelector('div.ghosted-input__field__main > input')` and script worked out as expected - email field value updated, submit form includes updated email. Selector is from Chrome Dev Tools, trimmed to few last entries – amankkg Aug 01 '18 at 21:38
  • here is an example with full-length selector https://imgur.com/a/4MM3jc2 once input value is changed - further script should work for sure – amankkg Aug 01 '18 at 22:00
  • 1
    For anyone working with select boxes try this: `element.value = 'somevalue'; element.dispatchEvent(new Event('change'));` – dw1 Jun 23 '19 at 23:07
  • in my case I had to use `input` event for textareas and `blur` for inputs – josef Nov 12 '20 at 23:07
2

@Bandal react needs to be notified that the inputs value has changed. You will need to dispatch a change event after you have updated the value.

    document.querySelector('textarea').value = myValue;
    const event = new Event('input', { bubbles: true })
    document.querySelector('textarea').dispatchEvent(event)

Original answer here

stwilz
  • 2,226
  • 2
  • 21
  • 24