winzik/skeleton-chrome/lib/i18n.js

19 lines
812 B
JavaScript

// Translates an extension page: every element with data-i18n="key" gets the text of _locales/<lang>/messages.json,
// data-i18n-attr="placeholder:key,title:key2" fills attributes. The <html lang> follows the browser's language.
export function t(key, substitutions) {
return chrome.i18n.getMessage(key, substitutions) || key;
}
export function translatePage(root = document) {
document.documentElement.lang = chrome.i18n.getUILanguage();
for (const node of root.querySelectorAll('[data-i18n]')) {
node.textContent = t(node.dataset.i18n);
}
for (const node of root.querySelectorAll('[data-i18n-attr]')) {
for (const pair of node.dataset.i18nAttr.split(',')) {
const [attr, key] = pair.split(':').map((s) => s.trim());
if (attr && key) node.setAttribute(attr, t(key));
}
}
}