fhefh2015
12/12/2010 - 5:33 PM

Easy i18n for your Chrome extensions and apps' DOM.

Easy i18n for your Chrome extensions and apps' DOM.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-i18n="dir=@@bidi_dir, lang=@@IETF_lang_tag"> <!--lang and dir attributes on the html root node are internationalized-->
<head>
<meta charset="utf-8"/>
<title data-i18n="title"/> <!--__MSG_title__ is internationalized in the title-->
</head>
<!--
	You usually won't use Chrome DOM i18n as shown in the following element.
	It's just to help you get a feel for the syntax.
-->
<body data-i18n="foo, 3=bar, baz, 2=foobar, some-attr=blah"> <!--__MSG_blah__ is internationalized in the "some-attr" attribute on the body node-->
<!--MSG_foo__ is internationalized here-->
<h1 data-i18n="title"/>
<!--__MSG_foobar__ is internationalized here -->
<p data-i18n="lorem_ipsum"/>
<!--__MSG_bar__ is internationalized here -->
<p data-i18n="lorem_ipsum"/>
<!--__MSG_baz__ is internationalized here-->
</body>
<script type="application/ecmascript" src="chrome-i18n.js"/>
</html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="__MSG_@@bidi_dir__" lang="__MSG_@@IETF_lang_tag__">
<head>
<meta charset="utf-8" />
<title>__MSG_title__</title>
</head>
<body some-attr="__MSG_blah__">
__MSG_foo__
<h1>__MSG_title__</h1>
__MSG_foobar__
<p>__MSG_lorem_ipsum__</p>
__MSG_bar__
<p>__MSG_lorem_ipsum__</p>
__MSG_baz__
</body>
<script type="application/ecmascript" src="chrome-i18n.js"></script>
</html>
/* Chrome DOM i18n: Easy i18n for your Chrome extensions and apps' DOM.
 * 2011-06-22
 *
 * By Eli Grey, http://eligrey.com
 * Public Domain.
 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 */

/*jslint laxbreak: true, strict: true*/
/*global self, chrome, document*/

(function (document) {
	"use strict";
	var
		i18n = self.i18n = function(key, substitutions) {
			if (key === "@@IETF_lang_tag") {
				return i18n("@@ui_locale").replace(/_/g, "-");
			}
			return chrome.i18n.getMessage(key, substitutions);
		}
		, localeText = document.querySelectorAll("[data-i18n]")
		, i = localeText.length
		, j, elt, terms, term, child, len, key, substitutions
	;
	while (i--) {
		elt = localeText.item(i);
		terms = elt.dataset.i18n.split(/\s*,\s*/);
		delete elt.dataset.i18n;
		child = j = 0;
		len = terms.length;
		for (; j < len; j++) {
			term = terms[j].split(/\s*=\s*/);
			if (term.length > 1 && isNaN(term[0])) {
				elt.setAttribute(term[0], i18n(term[1]));
			} else {
				if (term.length === 1) {
					child++;
				} else {
					child = +term[0];
				}
				elt.insertBefore(
					  document.createTextNode(i18n(term[term.length - 1]))
					, elt.children.item(child - 1)
				);
			}
		}
	}
}(document));