Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type text into a React input using javascript (Tampermonkey script)?

I'm trying to make a Tampermonkey script that'll automatically enter text into some form input fields.

Normally, you can do this with just:

myElement.value = "my new text"

Problem is, this form is using React, and I can't directly change the value, since it doesn't set the React state.. How can I enter my desired data into these React components in my Tampermonkey script?

like image 561
Andrio Avatar asked Aug 31 '18 17:08

Andrio


2 Answers

The answer could be found there https://github.com/facebook/react/issues/11488#issuecomment-347775628

let input = someInput; 
let lastValue = input.value;
input.value = 'new value';
let event = new Event('input', { bubbles: true });
// hack React15
event.simulated = true;
// hack React16 内部定义了descriptor拦截value,此处重置状态
let tracker = input._valueTracker;
if (tracker) {
  tracker.setValue(lastValue);
}
input.dispatchEvent(event);
like image 171
fengxing Avatar answered Sep 28 '22 15:09

fengxing


React doesn't expose component instances, so they aren't reachable without tampering an application on initialization, if this is possible.

Input values should be changed like they would be with vanilla JavaScript, by emitting DOM events.

React provides utility library that has helper functions to do that.

Here's an example. An input:

<input id="input" value={this.state.name} onChange={e => this.setState({ name: e.target.value })} />

And user script that runs after React application initialization:

import { Simulate } from 'react-dom/test-utils';

const input = document.getElementById('input');
input.value = 'Foo';
Simulate.change(input);
like image 42
Estus Flask Avatar answered Sep 28 '22 14:09

Estus Flask