chrome扩展:在DOM变化时运行观察器

问题描述 投票:0回答:1

在我的浏览器扩展中,我想在每次DOM内容发生变化时运行一些代码。我试过把这个

var observer = new MutationObserver((mutationsList) => {
  for(var mutation of mutationsList) {
    console.log(`${mutation.type} has been changed.`);
  }
});
const config = { attributes: true, childList: true, characterData: true };
observer.observe(document.body, config);

进入 content_script但观察者从来没有触发。

有什么提示吗?

google-chrome-extension mutation-observers
1个回答
0
投票

因为它从来没有触发过,我建议你修改一下你的 manifest.json 文件,以便在构建任何DOM之前运行。

例子 manfest.json

"content_scripts": [
{
  "matches": [ // your matches ],
  "run_at": "document_start",
  "js": ["content.js"]
}]

参考资料。https:/developer.chrome.comextensionscontent_scripts#run_time。

我还建议添加 subtree : true 到你的config对象中,以确保所有的死者的 document.body 被看。

© www.soinside.com 2019 - 2024. All rights reserved.