userscripts/zhihu_sticker_replacer.js

64 lines
2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// ==UserScript==
// @name Zhihu Image URL Replacer
// @namespace https://tampermonkey.net/
// @version 1.0
// @description Replace a specific Zhihu image URL with another one
// @match https://www.zhihu.com/*
// @match https://zhuanlan.zhihu.com/*
// @grant none
// ==/UserScript==
// 此脚本用于将知乎的「惊喜」表情替换为旧版
// 作者与原专栏https://zhuanlan.zhihu.com/p/1997308999595483524
(function () {
'use strict';
const OLD_URL = 'https://pic1.zhimg.com/v2-5c9b7521eb16507c9d2f747f3a32a813.png';
const NEW_URL = 'https://pic2.zhimg.com/v2-3846906ea3ded1fabbf1a98c891527fb.png';
function replaceImages(root = document) {
// Replace <img src="">
const imgs = root.querySelectorAll(`img[src="${OLD_URL}"]`);
imgs.forEach(img => {
img.src = NEW_URL;
});
// Replace srcset (Zhihu often uses this)
const srcsetImgs = root.querySelectorAll('img[srcset]');
srcsetImgs.forEach(img => {
if (img.srcset.includes(OLD_URL)) {
img.srcset = img.srcset.replaceAll(OLD_URL, NEW_URL);
}
});
// Replace background-image URLs
const elements = root.querySelectorAll('*');
elements.forEach(el => {
const bg = getComputedStyle(el).backgroundImage;
if (bg && bg.includes(OLD_URL)) {
el.style.backgroundImage = bg.replaceAll(OLD_URL, NEW_URL);
}
});
}
// Initial run
replaceImages();
// Observe dynamically loaded content
const observer = new MutationObserver(mutations => {
for (const m of mutations) {
m.addedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
replaceImages(node);
}
});
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
})();