在页面更改时运行脚本

Run script on page change

本文关键字:运行 脚本      更新时间:2023-09-26

我做了一个简单的chrome扩展,它在页面加载时运行内容脚本。它改变了img标记的src属性。如何让它在每次网站获得新的img标签时运行?例如,如果你在脸书上向下滚动,添加了新内容,我想把这些新图片改成我自己的。也许还有更好的方法?提前谢谢。

我会创建一个突变观测器,并将其添加到页面加载后注入的内容脚本中。

下面的代码正在侦听添加到body元素中的图像,并且每秒触发一个事件来模拟添加到DOM 中的图像

// select the target node
var target = document.querySelector('body');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      var nodes = mutation.addedNodes;
      var node;
      for(var n = 0; node = nodes[n], n < nodes.length; n++) {
          if(node.tagName == "IMG") {
            console.log("Image found");
          }
      };
    });
});
// configuration of the observer:
var config = { attributes: false, childList: true, subtree: true, characterData: false };
// pass in the target node, as well as the observer options
observer.observe(target, config);

setInterval(function() {
  var i = new Image();
  document.body.appendChild(i);
}, 1000);