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?
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With