2015-11-02 155 views
0

我制作了一个简单的扩展程序,可在页面加载时运行内容脚本。它改变了img标签的src属性。每当网站获得新的img标签时,如何让它运行?例如,如果您在Facebook上向下滚动新内容,我想将这些新图像更改为我自己的图像。也许有更好的方法?提前致谢。更改页面上的运行脚本

+0

还有许多其他的例子采用MutationObserver的,并且还包装库。 – wOxxOm

回答

2

我会创建一个mutation observer并将其添加到页面加载后注入的内容脚本中。

下面的代码正在监听的图像被添加到主体元件,和一个触发事件的每个第二模拟的图像被添加到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); 
+0

我在控制台中没有任何消息。 –

+0

你看到他们加载:https://jsbin.com/faqipi/latest – Kinlan

+0

在这里它的工作原理,但不是在Facebook或谷歌图形。 –