Trigger state change of a React component from Chrome extension on a Facebook post

Viewed 807

I'm doing a Chrome plugin for Facebook and I want to modify a post using external javascript. I can change the textContent of a span but the state is not changed and the Save button is not activated.

Facebook Post

The html looks like that :

<div class="" data-block="true" data-editor="1477r" data-offset-key="a699d-0-0">
  <div data-offset-key="a699d-0-0" class="_1mf _1mj">
    <span data-offset-key="a699d-0-0">
      <span data-text="true">test</span>
    </span>
  </div>
</div>

The component in React Developper Tools : [React component[2]

I profiled a change of the text and this is the result for a 6 ms timeline activating the save button. `Profiling

There are ways to modify a React input but did not found ways for my problem :

How can you change a Facebook post and his state with external javascript?

What would you do?

2 Answers

That’s not possible, you can’t imperatively mutate a React element tree from outside the app. You’d have to declaratively render a tree, either by modifying Facebook’s frontend code (beware of legal ramifications) or implementing your own post UI.

While it's nearly impossible to change the state of React component from your plugin, nothing stops you from emulating user's input by sending keystrokes, mouse clicks etc. The only thing you need it to figure out - which DOM-element listens to these events (not necessary one of those 4 in you question).


About the possibility of direct state change: let's say the component you need to changes is a functional one. Then it has a form of

Component() {
  const [state, setState] = useState(...)
  ...
  setState(something)
  ...
}

so you need to somehow access the setState function of the component. But how? It's private to the function call. If you think that instead you can call the useState directly, then be aware that in another component it will return another setState. I have no idea what would happen if you'll call useState outside of a component, but surely it will not be able to guess which setState you want.

If you want you can check the source code of react-devtools to find out how you can dig out the state from the depths of React... but would you really want to try? And for what? The next time Facebook or React will be updated your code will definitely break.

Related