The original question asked has been answered. In addition, someone outside of Stackoverflow has provided a full solution to what I was trying to achieve with my script, which I have added as an answer to my question. The script itself and a summary of the specific problem it solves is detailed in my own answer.
Original Question:
I'm not a programmer, unfortunately, so my experience is very limited.
My browser overwrites a correct img
src
with an incorrect src
a couple of seconds after it starts.
My script's intended function is a work-around to immediately replace the broken src
with the correct src
again, at the time my browser overwrites the correct src
.
function getElementsBySrc(srcValue) {
var nodes = [];
var e = document.getElementsByTagName('img');
for (var i = 0; i < e.length; i++) {
if (e[i].hasAttribute('src') && e[i].getAttribute('src') == srcValue) {
nodes.push(e[i]);
}
}
return nodes;
}
function initMod(){
if(!document.querySelector("#browser")){
setTimeout(initMod, 1000);
return;
}
var targetNode = document.getElementsByTagName('img');
var config = { attributes: true, childList: false, subtree: false, characterData: false };
var callback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
var n = getElementsBySrc('https://hyperspace.marquiskurt.net/icons/favicon-32x32.png');
for (var i = 0; i < n.length; i++) {
n[i].setAttribute('src', 'chrome://favicon/https://hyperspace.marquiskurt.net/app/');
}
}
}
};
var observer = new MutationObserver(callback);
observer.observe(targetNode, config);
}
initMod();
The script is loaded directly as my browser starts. My Chrome Devtools Console gives the error:
Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
as document.getElementsByTagName('img');
returns a list of elements, not a node, you can't use targetNode
(because it isn't a node)
Here I'm using document.querySelectorAll
instead, same result, but it has a forEach method that I use to create the mutation observers for each IMG
function initMod() {
if(!document.querySelector("#browser")){
setTimeout(initMod, 1000);
return;
}
const callback = (mutationsList, observer) => {
for(let mutation of mutationsList) {
if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
const n = getElementsBySrc('https://hyperspace.marquiskurt.net/icons/favicon-32x32.png');
for (let e of n) {
e.setAttribute('src', 'chrome://favicon/https://hyperspace.marquiskurt.net/app/');
}
}
}
};
const config = { attributes: true, childList: false, subtree: false, characterData: false };
document.querySelectorAll('img').forEach(targetNode => {
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
});
}