Skip to content

Instantly share code, notes, and snippets.

@WORMSS
Last active December 31, 2019 15:55
Show Gist options
  • Save WORMSS/d92424d8a371deacb37e to your computer and use it in GitHub Desktop.
Save WORMSS/d92424d8a371deacb37e to your computer and use it in GitHub Desktop.
Localisation of html pages for Chrome Extensions.
/**
* @author Colin Richardson
*
* @description this script in combination with a chrome extension enviroment adds i18n capabilities to html pages without jQuery.
* html elements will need a data-i18n tag with the message name and will be placed within the elements innerHTML attribute.
*
* This can be expanded/modified with the use of data-i18n-attr and place the name of the attribute you wish to assign the message to.
* EG: title, value, etc etc
* EG: data-i18n-attr="title", data-i18n-attr="value", etc etc
*
* For ease of use, the data-i18n attribute can accept {id} and {for} and this will read the elements id or for attributes and replace the message name.
* EG: {id}, sect_{id}, label_{for}_check, etc etc
* EG: data-i18n="{id}", data-i18n="sect_{id}", data-i18n="label_{for}_check", etc etc
* Will turn into data-i18n="options", data-i18n="sect_options", data-i18n="label_options_check", etc etc
*
*
* @usage window.onload = wss.i18n;
* @usage window.onload = function() {
* ...
* wss.i18n();
* ...
* }
*
* @html page
**/
var wss = wss || {};
Object.defineProperty(wss, 'i18n', { value: function() {
Array.prototype.forEach.call(document.getElementsByTagName('*'), function (el) {
if ( el.hasAttribute('data-i18n') ) {
el[el.getAttribute('data-i18n-attr') || 'innerHTML'] = chrome.i18n.getMessage(el.getAttribute('data-i18n').replace(/\{id\}/g, el.id).replace(/\{for\}/g, el.getAttribute('for')));
}
})
}});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment