首页 > 解决方案 > 支持 HTML 页面中的本地化(弹出/内容/选项)

问题描述

有没有一种简单的方法使弹出/内容/选项页面多语言

文档给我的印象是,唯一的办法就是使用 JS 将本地化的字符串添加到 html 中。这会使事情变得非常麻烦和复杂(每个节点都需要一个 ID 或类等)
我已经尝试在 HTML 中使用,但它只是显示标签本身(似乎只有 css 支持标签)。 所以现在我写了这个小片段,它检查页面的每个元素并用来自的字符串替换所有元素:${tag}
${tag}chrome.i18n.getMessage(tag)

!function()
{
  let i18nRegExp = /\$\{([^}]+)\}/g,
      cache = {},
      i18n = function(a,b)
      {
        return cache[b] || (cache[b] = chrome.i18n.getMessage(b) || a);
      };

  !function loop(node)
  {
    if (node.attributes)
      for(let i = 0; i < node.attributes.length; i++)
        node.attributes[i].value = node.attributes[i].value.replace(i18nRegExp, i18n);

    if (!node.childNodes.length)
      node.textContent = node.textContent.replace(i18nRegExp, i18n);
    else
      for(let i = 0; i < node.childNodes.length; i++)
        loop(node.childNodes[i]);
  }(document.body.parentNode);
}();

有更好的方法吗?

标签: javascriptgoogle-chrome-extensionfirefox-addonfirefox-addon-webextensionsthunderbird-webextensions

解决方案


treestyletab 扩展的开发人员创建了一个用于本地化 HTML 的简单库,称为webextensions-lib-l10n


推荐阅读