```// This script changes the font of all Mandarin character on a page.
const url = chrome.runtime.getURL('font/Hanzi-Pinyin-Font.top.ttf');
const fontFace = ` @font-face { font-family: ZhongwenFont; src: url(${url}) } `;
window.onload = function () { const styleSheet = document.createElement("style"); styleSheet.innerHTML = fontFace document.head.appendChild(styleSheet); // For static pages, handle all elements: document.body.querySelectorAll("").forEach(handleElement); // support for dynamic pages // For dynamic apps, like Twitter, observe all DOM mutations henceforth within document body: addMutationObserver();
}
function handleText(textNode) { // Regular expression to match all Chinese characters const regex = /[\p{Script=Han}]+/gu; if (regex.test(textNode.nodeValue)) { const { style } = textNode.parentElement; style.fontFamily = 'ZhongwenFont'; style.fontSize = "large" } }
function addMutationObserver() { const observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { mutation.target.querySelectorAll("").forEach(handleElement); }); }); observer.observe(document.body, { subtree: true, childList: true }); }
function handleElement(e) { e.childNodes.forEach((child) => { if (child && !isUserInput(child) && child.nodeName === "#text") { handleText(child); } }); }
// Some helper functions used by the code above: function isUserInput(node) { const tagName = node.tagName ? node.tagName.toLowerCase() : ""; return ( tagName == "input" || tagName == "textarea" || isInsideContentEditable(node) ); }
function isInsideContentEditable(node) { while (node.parentNode) { if (node.contentEditable === "true") { return true; } node = node.parentNode; } return false; }```