Warm tip: This article is reproduced from stackoverflow.com, please click
google-chrome google-chrome-extension html internationalization javascript

Internationalization of HTML pages for my Google Chrome Extension

发布于 2020-04-13 09:23:28

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?

Questioner
c00000fd
Viewed
59
ahmd0 2014-09-25 11:19

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();