51 lines
1.7 KiB
JavaScript
51 lines
1.7 KiB
JavaScript
function localizeHtmlPage() {
|
|
if (typeof chrome === 'undefined' || !chrome.i18n) {
|
|
// Mock chrome.i18n API if not available (e.g., running in a regular browser)
|
|
const script = document.createElement('script');
|
|
script.src = 'js/i18n-mock.js';
|
|
script.onload = function() {
|
|
console.log('Loaded mock i18n API');
|
|
localizeHtmlPage(); // Re-run localization after mock is loaded
|
|
};
|
|
document.head.appendChild(script);
|
|
return; // Exit to prevent running without the mock
|
|
}
|
|
|
|
const i18nRegex = /__MSG_(\w+)__/g;
|
|
|
|
function replaceMsg(match, p1) {
|
|
try {
|
|
return p1 ? chrome.i18n.getMessage(p1) : match;
|
|
} catch (e) {
|
|
console.warn(`Could not find message for: ${p1}`);
|
|
return match;
|
|
}
|
|
}
|
|
|
|
const walker = document.createTreeWalker(
|
|
document.documentElement,
|
|
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
|
|
null,
|
|
false
|
|
);
|
|
|
|
let node;
|
|
while (node = walker.nextNode()) {
|
|
if (node.nodeType === Node.ELEMENT_NODE) {
|
|
for (const attr of node.attributes) {
|
|
if (i18nRegex.test(attr.value)) {
|
|
attr.value = attr.value.replace(i18nRegex, replaceMsg);
|
|
}
|
|
}
|
|
} else if (node.nodeType === Node.TEXT_NODE) {
|
|
if (i18nRegex.test(node.nodeValue)) {
|
|
node.nodeValue = node.nodeValue.replace(i18nRegex, replaceMsg);
|
|
}
|
|
}
|
|
}
|
|
|
|
document.documentElement.lang = chrome.i18n.getUILanguage().split('-')[0];
|
|
document.title = document.title.replace(i18nRegex, replaceMsg);
|
|
}
|
|
|
|
document.addEventListener('DOMContentLoaded', localizeHtmlPage); |