简体   繁体   中英

Chrome Extension Doesn't Work After Scrolling

I have a question regarding a Chrome extension which I am making. 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/

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. 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. A more efficient solution could be done using 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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