gpt4 book ai didi

javascript - 在页面更改时运行脚本

转载 作者:行者123 更新时间:2023-12-02 15:29:10 24 4
gpt4 key购买 nike

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

最佳答案

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

下面的代码正在监听添加到 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);

关于javascript - 在页面更改时运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33476834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com