My Octopress Blog

A blogging framework for hackers.

Translating HTML in a Chrome Extension

I have been working on updating my Live CSS Editor chrome extension to add some new features, and in the process, I figured I would set it up so that it could be translated into other languages.

Chrome has a pretty nice translation setup, which you can learn more about on their internationalization docs. It works great for any javascript, css or manifest files, but I wanted to translate the text in the HTML options page.

It turned out to be pretty easy.

First, I used an HTML data attribute to specify what the messagename would be for each area. If the element wasn’t already wrapped in an HTML tag that was specific enough, I just wrapped it in a span.

For example:

<h1>Live CSS Editor Options</h1>


<h1 data-message="optionsHeaderTitle">Live CSS Editor Options</h1>

This lets me specify what key each section would use from the messages hash. Once that’s setup, a few lines of Javascript does the replacement for me as soon as the page is loaded:

var objects = document.getElementsByTagName('*'), i;
  for(i = 0; i < objects.length; i++) {
    if (objects[i].dataset && objects[i].dataset.message) {
      objects[i].innerHTML = chrome.i18n.getMessage(objects[i].dataset.message);

This code loops through each element on the page, and if the element has a data-message attribute, it swaps the content of the element with the translation from the messages hash.

Of course, for each messagename you’ve added to the page, you need to setup an equivalent entry in the messages.json file. For more information on this, checkout out the internationalization docs.

This is a fairly simple solution, and dosen’t cover every internationalization situation. However, for taking care of something like an options page, it works just right.