0

Let's say I want to develop a third party plugin, like a chrome extension. So I will have absolutely no privilege to change the javascript code of the page. All I can do is add things external to the page.

So I would use jQuery to manipulate the DOM. But if the page is rendered by react, what I did to the DOM would be erased in the react lifecycle. I see some tutorials teaching how to integrate jQuery in to a react app. But this is not what I need. Is there any way to manipulate the DOM without changing the original react code at all? Like registering a listener to the react engine or something?

All I think of is to use a setInterval or requestAnimationFrame loop to keep the DOM changed. But I still want to know if there is a better way.

Ru Lu
  • 11
  • 1
  • 1

1 Answers1

1

You can use MutationObserver to detect the moment DOM was modified and add your stuff again if it was removed.

let myStuff = $('<div>foo</div>');

const mo = new MutationObserver(() => {
  if (!document.contains(myStuff[0])) {
    insert();
  }
});

observe();

function insert() {
  mo.disconnect();
  myStuff.appendTo('.some.react.element');
  observe();
}

function observe() {
  mo.observe(document.body, {childList: true, subtree: true});
}

Another advanced approach is hooking into React itself via __REACT_DEVTOOLS_GLOBAL_HOOK__ in page context, it's also used by React DevTools, look for more info yourself if you aren't afraid to delve into the depths.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136