Internationalization of HTML pages for my Google Chrome Extension

拜拜、爱过 提交于 2020-06-07 13:35:30

问题


I found a very easy way to implement translation (or localization) of my Google Chrome Extension, but that seems to apply only to .json, css and js files.

But how to localize my html content, say in the popup or an options window?


回答1:


What you would do is this.

First, in your HTML use the same syntax as Chrome requires anywhere else. So your basic popup.html will be:

<!DOCTYPE html>
<html>
<head>
<title>__MSG_app_title__</title>
</head>
<body>

<a href="http://example.com/" title="__MSG_prompt001__">__MSG_link001__</a>

<!-- Need to call our JS to do the localization -->
<script src="popup.js"></script>
</body>
</html>

Then provide the usual translation in _locales\en\messages.json:

{
    "app_title": {
        "message": "MyApp",
        "description": "Name of the extension"
    },
    "link001": {
        "message": "My link",
        "description": "Link name for the page"
    },
    "prompt001": {
        "message": "Click this link",
        "description": "User prompt for the link"
    }
}

And finally your popup.js will perform the actual localization:

function localizeHtmlPage()
{
    //Localize by replacing __MSG_***__ meta tags
    var objects = document.getElementsByTagName('html');
    for (var j = 0; j < objects.length; j++)
    {
        var obj = objects[j];

        var valStrH = obj.innerHTML.toString();
        var valNewH = valStrH.replace(/__MSG_(\w+)__/g, function(match, v1)
        {
            return v1 ? chrome.i18n.getMessage(v1) : "";
        });

        if(valNewH != valStrH)
        {
            obj.innerHTML = valNewH;
        }
    }
}

localizeHtmlPage();



回答2:


Building from ahmd0's answer. Use a data attribute to allow a hard-coded fallback.

<!DOCTYPE html>
<html>
    <head>
        <title data-localize="__MSG_app_title__">My Default Title</title>
    </head>
    <body>
        <a href="http://example.com/" title="__MSG_prompt001__" data-localize="__MSG_link001__">Default link text</a>

        <script src="localize.js"></script>
    </body>
</html>

Then provide the usual translation in _locales\en\messages.json:

{
    "app_title": {
        "message": "MyApp",
        "description": "Name of the extension"
    },
    "link001": {
        "message": "My link",
        "description": "Link name for the page"
    },
    "prompt001": {
        "message": "Click this link",
        "description": "User prompt for the link"
    }
}

And finally your localize.js will perform the actual localization:

function replace_i18n(obj, tag) {
    var msg = tag.replace(/__MSG_(\w+)__/g, function(match, v1) {
        return v1 ? chrome.i18n.getMessage(v1) : '';
    });

    if(msg != tag) obj.innerHTML = msg;
}

function localizeHtmlPage() {
    // Localize using __MSG_***__ data tags
    var data = document.querySelectorAll('[data-localize]');

    for (var i in data) if (data.hasOwnProperty(i)) {
        var obj = data[i];
        var tag = obj.getAttribute('data-localize').toString();

        replace_i18n(obj, tag);
    }

    // Localize everything else by replacing all __MSG_***__ tags
    var page = document.getElementsByTagName('html');

    for (var j = 0; j < page.length; j++) {
        var obj = page[j];
        var tag = obj.innerHTML.toString();

        replace_i18n(obj, tag);
    }
}

localizeHtmlPage();

The hard-coded fallback avoids the i18n tags being visible while the JavaScript does the replacements. Hard-coding seems to negate the idea of internationalisation, but until Chrome supports i18n use directly in HTML we need to use JavaScript.




回答3:


As RobW noted in a comment, a feature request for adding i18n support in HTML using the same mechanism was created, but it has since then been rejected due to performance and security concerns. Therefore you can't use the same approach.

The issue mentions one possible workaround: to have separate HTML pages per language and switch between them in the manifest:

  "browser_action": {
    "default_popup": "__MSG_browser_action_page__"
  }

But if that's not a suitable approach, the only way is to translate the page dynamically via JavaScript. You mention a solution the simplest approach, by just tagging elements to translate with ids and replacing them on page load.

You can also employ more sophisticated tools like webL10n in parallel with Chrome's approach. Note that you should probably still minimally implement Chrome's approach, so that Web Store knows that the item is supporting several languages.




回答4:


Plain an simple:


{
  "exmaple_key": {
    "message": "example_translation"
  }
}


<sometag data-locale="example_key">fallback text</sometag>


document.querySelectorAll('[data-locale]').forEach(elem => {
  elem.innerText = chrome.i18n.getMessage(elem.dataset.locale)
})




回答5:


Rather than parsing the full DOM, just add a class "localize" to the elements that have to be translated and add a data attribute data-localize="open_dashboard"

<div class="localize" data-localize="open_dashboard" >
  Open Dashboard
</div>

JavaScript :

$('.localize').each(function(index,item){
    var localizeKey = $(item).data( 'localize' );
    $(item).html(chrome.i18n.getMessage(localizeKey));
});

'_locales/en/messages.json' file

{
    "open_dashboard": {
        "message": "Open Dashboard",
        "description": "Opens the app dashboard"
    }
}



回答6:


One of the ways to localize your content in popup html is to fetch it from javascript onLoad. Store the strings in the _locales folder under various languages supported by you as mentioned here and do chrome.i18n.getMessage("messagename") to fetch and load the variable strings and set them using javascript/jquery onLoad function for each html element from your background.js or whatever js you load before your html pages loads.




回答7:


I faced the same problem, but I solved it with a simple approach using custom data attributes.

Implement a localizing class that uses chrome.i18n and call it in the DOMContentLoaded event. In HTML, mark up the element you want to localize with the data-chrome-i18n attribute. (This attribute name is tentatively named.) Specifying the message name as the value of this attribute localizes the text content of the element. If you want to localize an attribute, specify it in the format attribute_name=message_name. Multiple specifications can be specified by separating them with ;.

const i18n = (window.browser || window.chrome || {}).i18n || { getMessage: () => undefined };

class Localizer {
  constructor(options = {}) {
    const { translate = Localizer.defaultTranslate, attributeName = Localizer.defaultAttributeName, parse = Localizer.defaultParse } = options;
    this.translate = translate;
    this.attributeName = attributeName;
    this.parse = parse;
  }
  localizeElement(element) {
    for (const [destination, name] of this.parse(element.getAttribute(this.attributeName))) {
      if (!name)
        continue;
      const message = this.translate(name) || '';
      if (!destination) {
        element.textContent = message;
      }
      else {
        element.setAttribute(destination, message);
      }
    }
  }
  localize(target = window.document) {
    const nodes = target instanceof NodeList ? target : target.querySelectorAll(`[${CSS.escape(this.attributeName)}]`);
    for (const node of nodes)
      this.localizeElement(node);
  }
}
Localizer.defaultTranslate = i18n.getMessage;
Localizer.defaultAttributeName = 'data-chrome-i18n';
Localizer.defaultParse = (value) => {
  return (value || '').split(';').map(text => (text.includes('=') ? text.split('=') : ['', text]));
};

const localizer = new Localizer();
window.addEventListener('DOMContentLoaded', () => {
  localizer.localize();
});
<!DOCTYPE html>
<html data-chrome-i18n="lang=@@ui_locale">

<head>
  <meta charset="UTF-8" />
  <title data-chrome-i18n="extensionName"></title>
</head>

<body>
  <p data-chrome-i18n="foo;title=bar;lang=@@ui_locale"></p>
</body>

</html>

There are several things to consider to solve this problem.

  • Use chrome.i18n (Many people will want to aggregate in messages.json.)
  • Supports attributes as well as element content
  • Supports not only popup but also options page
  • Rendering performance
  • Security

First, the approach of switching HTML for each language in manifest.json does not work. Even if you give __MSG_*__ to the default_popup field, popup will still show the error "ERR_FILE_NOT_FOUND". I don't know why. There is no detailed reference to default_popup in the Chrome extensions Developer Guide, but MDN mentions that it is a localizable property. Similarly, if you give __MSG _*__ to the page field in options_ui, the extension itself will fail to load.

I intuitively felt that the approach of replacing __MSG_*__ in HTML and rewriting the result usinginnerHTML had performance and security problems.




回答8:


A workaround to avoid replacements:

Use a simple "redirect"

It works for popups and options

  1. In your manifest, declare the default popup

    "default_popup": "popup/redirect.html"
    
  2. The popup/redirect.html is almost empty. It just includes the script link to the redirect script

        <!DOCTYPE html>
        <html>
    <head></head>
    <body>
        <script src="redirect.js"></script>
    </body>
    

  3. The popup/redirect.js file is very simple too:

    var currentlang = chrome.i18n.getMessage("lang");
    var popupUrl = chrome.runtime.getURL("popup/popup-"+currentlang+".html");
    window.location.href = popupUrl;
    
  4. Create multiple popups, already localized:

    • popup-fr.html
    • popup-en.html
  5. Go into each of your messages.json files (in _locales) and add a "lang" message with the current language abbreviation as value: en for the english json, fr in the french json...

    • example for _locales/en/message.json:

       "lang": {
       "message": "en",
       "description": "Locale language of the extension."
       },
      

A simple workaround for very small project... definitely not a good choice for large ones. And it also works for Option pages.




回答9:


Another workaround - you can use content property in css with __MSG_myText inside.



来源:https://stackoverflow.com/questions/25467009/internationalization-of-html-pages-for-my-google-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!