Skip to content

Instantly share code, notes, and snippets.

@snipsnipsnip
Forked from eligrey/chrome-i18n.js
Last active January 11, 2020 11:37
Show Gist options
  • Save snipsnipsnip/4c980865d968c4ed8441dca2fd52fce1 to your computer and use it in GitHub Desktop.
Save snipsnipsnip/4c980865d968c4ed8441dca2fd52fce1 to your computer and use it in GitHub Desktop.
Easy i18n for your Chrome extensions and apps' DOM.
/*
* A cut-down i18n utility. @snipsnipsnip
* Based on Chrome DOM i18n By Eli Grey, http://eligrey.com
* Public Domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
"use strict";
for (let e of document.querySelectorAll("[data-i18n]")) {
for (let [attr, key] of Object.entries(e.dataset)) {
let msg = attr.startsWith("i18n") && key && browser.i18n.getMessage(key);
if (!msg) {
key && console.log('skipped', { attr, key });
} else if (attr.length === 4) {
e.appendChild(document.createTextNode(msg));
} else {
e.setAttribute(attr.substr(5), msg);
}
}
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="__MSG_@@bidi_dir__">
<head>
<meta charset="utf-8" />
<title>__MSG_title__</title>
</head>
<body some-attr="__MSG_blah__">
<h1>__MSG_title__</h1>
<p>__MSG_lorem_ipsum__</p>
<p>__MSG_lorem_ipsum__</p>
__MSG_foo__
</body>
<script type="application/ecmascript" src="chrome-i18n.js"></script>
</html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-i18n="" data-i18n.dir="@@bidi_dir"> <!-- 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" data-i18n.some-attr="blah"> <!--__MSG_blah__ is internationalized in the "some-attr" attribute on the body node-->
<h1 data-i18n="title"/>
<p data-i18n="lorem_ipsum"/>
<p data-i18n="lorem_ipsum"/>
<!--__MSG_foo__ is internationalized here-->
</body>
<script src="chrome-i18n.js"/>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment