Manipulate the DOM using jQuery, without changing the react code

泪湿孤枕 提交于 2021-02-11 12:33:52

问题


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.


回答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.



来源:https://stackoverflow.com/questions/63879769/manipulate-the-dom-using-jquery-without-changing-the-react-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!