简体   繁体   English

Chrome 扩展在滚动后不起作用

[英]Chrome Extension Doesn't Work After Scrolling

I have a question regarding a Chrome extension which I am making.我有一个关于我正在制作的 Chrome 扩展程序的问题。 I tried creating a similar extension to this which would replace all images on the website with cat images:我尝试创建一个类似的扩展,它将用猫图像替换网站上的所有图像:

https://blog.lateral.io/2016/04/create-chrome-extension-modify-websites-html-css/ https://blog.lateral.io/2016/04/create-chrome-extension-modify-websites-html-css/

I tried it on Facebook.我在脸书上试过了。

The code is very simple:代码非常简单:

var images = document.getElementsByTagName('img');
for (var i = 0, l = images.length; i < l; i++) {
  images[i].src = 'http://placekitten.com/' + images[i].width + '/' + images[i].height;
}

The issue I have is that it only works with the images that first appear on Facebook and after scrolling for a bit it stops replacing images.我遇到的问题是它只适用于首次出现在 Facebook 上的图像,滚动一段时间后它会停止替换图像。 Also, when scrolling back up the images that were initially replaced are now back to original.此外,当向上滚动时,最初替换的图像现在又回到了原始图像。

Is there any way I could fix this so the extension works throughout the whole site even when new images load after scrolling down?有什么办法可以解决这个问题,即使在向下滚动后加载新图像时,扩展程序也可以在整个站点中工作? Thank you!谢谢!

You need to make sure that your code is re-run when new images appear.您需要确保在出现新图像时重新运行您的代码。 The easiest solution would be to have a setInterval() calling it periodically.最简单的解决方案是让 setInterval() 定期调用它。 A more efficient solution could be done using Mutation Observers.使用 Mutation Observers 可以完成更有效的解决方案。 There are probably other ways to detect new images appearing, like checking the height of the window or listening to user actions (like scrolling).可能还有其他方法可以检测出现的新图像,例如检查窗口的高度或监听用户操作(例如滚动)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM