I'm trying to create a chrome extension to interact with twitch website.
So far, it works most of the time, but randomly I get an error.
Here is the code of the content script:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++){
if (mutation.addedNodes[i].nodeType == 1){
if (mutation.addedNodes[i].hasAttribute("aria-describedby")){
mutation.addedNodes[i].querySelector("button").click();
}
}
}
});
});
window.addEventListener('load', function () {
node = document.querySelector("[data-test-selector='community-points-summary']");
observer.observe(node, { subtree: true, childList: true });
});
The problem is sometimes "node" is null, which creates an error:
Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
My assumption is that the page is not fully loaded, then the querySelector fails to get the DOM. But I don't understand why this is happening, as I am in the "load" function, which should be fired only when the page is fully loaded.
It's a bit difficult to debug because it is mostly random. If I refresh the twitch page, then the script works. I feel like if the page is in the cache, I don't really have this issue, but I'm not sure.
Thanks.