Type text into a React input using javascript (Tampermonkey script)?
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?
2 Answers
2
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);
That utility library looks like what I need, but I'm not sure if it's possible to import that into my Tampermonkey script.
– Andrio
Sep 12 at 17:03
@Andrio Most React libs are UMD modules that are exposed as globals in non-modular environment. This one should be available
window.ReactTestUtils on react-dom load.– estus
Sep 12 at 17:07
window.ReactTestUtils
react-dom
class HelloWorld extends React.Component
constructor(props)
super(props);
this.state = firstname: '';
this.handleChange = this.handleChange.bind(this);
handleChange(e)
this.setState(firstname: e.target.value)
render()
return(<div><input id="firstname" type=text onChange=(e) =>this.handleChange() value=this.state.firstname ></div>)
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Just to clarify, I can't modify the React components at all. This is purely for a tampermonkey script running on the client.
– Andrio
Aug 31 at 19:18