I am writing a userscript that will run whenever I visit our JIRA server. It will swap out the avatar images for users with images from our company's ID badging photo store. This way, the entire organization does not need to upload their images onto the JIRA server separately for the user icons to be readily recognizable. I can use jQuery to alter the 'src' attribute of images already rendered into the DOM. However, the JIRA pages load dynamic content into divs and so on, so I am wondering if there is a way to attach an event handler that would trigger whenever the browser tries to fetch an image, and serve a different image from company server instead. The img tag contains the data attribute needed for me to map the image correctly. I just don't know what event to hook into.
The closest I could find is the "Grumpy cat" example on this page (landed there from this Stackoverflow comment), but it seems Mobify is no longer being maintained. What are the present-day options to tackle this use case?
Thanks!
You can use a deep (subtree) MutationObserver to watch for elements being added to the DOM. Whenever an element is added, look through it and its children for <img>
s, and perform the required replacement on each:
const transform = img => img.src = img.src.replace(/200x100/, '100x100');
new MutationObserver((mutations) => {
for (const { addedNodes } of mutations) {
for (const addedNode of addedNodes) {
if (addedNode.nodeType !== 1) continue;
const imgs = addedNode.querySelectorAll('img');
for (const img of imgs) {
transform(img);
}
if (addedNode.tagName === 'IMG') {
transform(addedNode);
}
}
}
})
.observe(document.body, { childList: true, subtree: true });
setTimeout(() => {
document.body.innerHTML += '<div><img src="https://via.placeholder.com/200x100"><div>';
});