简体   繁体   中英

Triggering Synthetic Event in React App

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}))

  • I've tried this from both the content-script environment and the actual page environment (via both an injected script that responds to postMessage and the Chrome console)
  • I've also tried triggering the event on the document , from each context.
  • Nothing seems to happen.

2) Same thing, but with VanillaJS event triggering. relevant StackOverflow question

  • also from both environments
  • Nothing happens

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).

  • Also does not work. The function executes fully and without errors, but there's no response from the application.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM