Create from ahmd0 answer. Use the data attribute to enable hard-code backups.
<!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 specify the normal 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 do the current 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();
A hard-coded backup eliminates the visibility of i18n shortcuts when JavaScript performs replacements. Hard coding seems to deny the idea of internationalization, but while Chrome does not support i18n directly in HTML, we need to use JavaScript.
Dan jones
source share