Reputation: 65
I'm trying to create a Chrome Extension that is able to change images of banner icons on a page. The .js waits for the window.onload to issue, then starts a mutationObserver for the div that contains the banners. If a change is detected, a for loop changes all the images.
My issue is that the mutationObserver is run before the div exists, meaning I run into a Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'
error.
How can I guarantee that this element has fully loaded in before my code executes?
I'm also having an issue where if I navigate the page and come back to the page with the banners, my code does not run. I believe this is caused by my "window.onload" function.
Here's my code for the chrome extension. Thank ya'll!
window.onload = () => {
const targetNode = document.getElementById('course-columns-current');
const config = { attributes: true, childLIst: true, subtree: true};
const callback = (observer) => {
const banners = document.getElementsByClassName("course-banner");
console.log("inside the callback!")
console.log(banners)
for (let i = 0; i < banners.length; i++) {
console.log(banners[i])
banners[i].style.backgroundImage = "url('https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh;0,0.190xh&resize=640:*')";
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
}
Upvotes: 1
Views: 66
Reputation: 65
To fix this, the solution ended up being replacing the observer target to document.body
.
Here's the updated and working code:
window.onload = () => {
const targetNode = document.body;
const config = { attributes: true, childLIst: true, subtree: true};
const callback = (observer) => {
const banners = document.getElementsByClassName("course-banner");
console.log("inside the callback!")
console.log(banners)
for (let i = 0; i < banners.length; i++) {
console.log(banners[i])
banners[i].style.backgroundImage = "url('https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh;0,0.190xh&resize=640:*')";
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
}
Upvotes: 1