且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Chrome扩展程序:在加载前修改DOM

更新时间:2023-12-05 21:49:40

您可以使用 document.addEventListener 以及 DOMNodeInserted 事件。这些节点将被构造,您将有机会在插入到DOM之前进行修改。

  function nodeInsertedCallback(event){
console.log(event);
};
document.addEventListener('DOMNodeInserted',nodeInsertedCallback);

 


My Chrome Extension should modify a DOM element before the DOM is fully constructed, and in the best scenario, right after this DOM element is constructed.

For example, if I have a in my document, I want to wait until it is constructed, then directly modify it, before the rest of the DOM is constructed.

But I only managed to access the DOM before the element is constructed and after the entire DOM is constructed.

So how do I listen to the construction of a special element ?

You can use document.addEventListener with the DOMNodeInserted event. The nodes will be constructed and you will have a chance to modify them before they are inserted into the DOM. Something like the following should work.

function nodeInsertedCallback(event) {
  console.log(event);
};
document.addEventListener('DOMNodeInserted', nodeInsertedCallback);