I'm writing a Chrome extension for Facebook and want to programmatically trigger the submission of the focused comment draft on a post. The default behavior is to submit when the user hits the Enter key, so I'm attempting to trick the Facebook UI into thinking that the user did so.
Facebook uses React and a contenteditable
div for comment forms.
Here's a set of things that I've tried:
1) jQuery Event triggering $('<the contenteditable div>').trigger($.Event('keydown', {which: 13}))
postMessage
and the Chrome console)document
, from each context.2) Same thing, but with VanillaJS event triggering. relevant StackOverflow question
3) At this point I realized that this is React and it uses it's own SyntheticEvents
, so I basically copy/pasted the Simulate
function from ReactTestUtils
that's supposed to help testing by simulating events and ran that within the page's environment (grabbing references to the required
objects via Facebook's frontend require
function).
I've tried this with mostly keydown
events, because that has the most listeners attached to it.
I'm aware of these questions, but they haven't helped my understanding: Force React to fire event through injected JavaScript
createElement('input'); target. value = newValue; const event = new Event('change', { bubbles: true }); Object. defineProperty(event, 'target', { writable: false, value: target }) const syntheticEvent = createSyntheticEvent(event) as React. ChangeEvent<typeof target>; onChange(syntheticEvent);
In React, an event handler is passed with an instance of SyntheticEvent , a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault() . In React, you cannot return false to prevent default behavior.
ReactJS implements a synthetic events system because that brings consistency and high performance to React apps and application UI. It helps to achieve consistency by normalizing native events so that they have the same properties across different browsers and platforms.
It's unclear based on your description whether or not this is an issue, but SyntheticEvent
has caused me pain before due to the fact that the object is reused. There's a note in the React docs about this:
If you want to access the event properties in an asynchronous way, you should call
event.persist()
on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.
If you aren't immediately using the event, or if you are trying to pass it into a new scope, you'll need to persist()
it.
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