Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internationalization of HTML pages for my Google Chrome Extension

Tags:

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?

like image 293
c00000fd Avatar asked Aug 23 '14 22:08

c00000fd


People also ask

What is internationalization in HTML?

Internationalization of HTML takes place at two levels: (1) the characters in the text (apart from the markup) should be able to represent non-western alphabets, such as Cyrillic, Arabic, Hebrew, Japanese, etc.; (2) in addition, for correct display and other operations, it is sometimes necessary to explicitly indicate ...

Do Chrome extensions use HTML?

Extensions are made of different, but cohesive, components. Components can include background scripts, content scripts, an options page, UI elements and various logic files. Extension components are created with web development technologies: HTML, CSS, and JavaScript.


2 Answers

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();
like image 126
ahmd0 Avatar answered Sep 22 '22 10:09

ahmd0


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)
})

like image 33
pykiss Avatar answered Sep 25 '22 10:09

pykiss