JavaScript - Tampermonkey script to observe changes on a page and edit it
The following example is Tampermonkey adds event listeners to elements in a page and also recurses into new iframes.
After installing the script, visit Google Search and search for “test” keyword to see source titles specified in script turned red.
Ensure to change data-added-makethisunique
to something else. For example, data-added-somethingelseunique
. This ensures the mutation observers are not added twice.
// ==UserScript==
// @name Modify Google search results.
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Adds event listener to elements in a page and also recurses into new iframes.
// @author [email protected]
// @match https://www.google.com/search?*
// @grant none
// ==/UserScript==
(function() {
const attrName = "data-added-makethisunique";
const titlesToTurnRed = [
"Dictionary.com",
"Fast.com",
"Wikipedia"
];
const replaceElementStr = function(element, testRegex, searchRegex, replaceStr) {
if (element.nodeType == 3) {
if (!testRegex.test(element.textContent)) {
return;
}
element.textContent = element.textContent.replace(searchRegex, replaceStr);
return
} else if (element.nodeType == 1) {
element.childNodes.forEach(function(node, index) {
replaceElementStr(node, testRegex, searchRegex, replaceStr);
});
}
};
const doSomething = function(element) {
replaceElementStr(element, /HELLO WORLD/i, /HELLO WORLD/ig, 'H3110 W0r1d');
[...element.querySelectorAll('span')].forEach(function(span, index) {
if (titlesToTurnRed.indexOf(span.textContent.trim()) == -1) {
return;
}
span.style.color = "red";
});
};
const addListenersToDocumentOnce = function(element) {
if (!element || element.getAttribute(attrName)) {
return;
}
element.setAttribute(attrName, "1");
doSomething(element);
addMutationObserver(element, function(mutation) {
if (mutation.target.tagName == "IFRAME") {
addListenersToDocumentOnce(mutation.target.contentDocument.body);
} else {
doSomething(mutation.target);
}
});
console.log("Added listener to element:", element);
};
const addMutationObserver = function(containerToObserve, callback) {
const observer = new MutationObserver(function(mutationList, observer) {
for (const mutation of mutationList) {
callback(mutation);
}
});
observer.observe(containerToObserve, {attributes: true, childList: true, subtree: true});
};
// Run on mutations
addListenersToDocumentOnce(document.body);
})();