Frontend API

Configuration options for the on-site Localize script

(not applicable in Mobile App projects)

Visit our Installation Guide for step-by-step instructions for adding our client-side JavaScript library to your site.

Below is the Localize snippet with the default library options. To get started with Localize, include this snippet within the <head> of all pages in your website.

<script src="https://global.localizecdn.com/localize.js"></script>
<script>!function(a){if(!a.Localize){a.Localize={};for(var e=["translate","untranslate","phrase","initialize","translatePage","setLanguage","getLanguage","detectLanguage","getAvailableLanguages","untranslatePage","bootstrap","prefetch","on","off","hideWidget","showWidget","getSourceLanguage"],t=0;t<e.length;t++)a.Localize[e[t]]=function(){}}}(window);</script>

<script>
  Localize.initialize({
    key: '[[app:key]]', 
    rememberLanguage: true,
    // other options go here, separated by commas
  });
</script>

The following are the available methods in the Localize object.

initialize()

Localize.initialize({options});

The following are the available options for the initialize() method.
NOTE: All option names are case-sensitive!!

Only the first option is required, all others are optional.

key

Required. Your Project Key. Find it here.


autoApprove

Defaults to false.
If true and you have machine translations enabled, any new phrases found in your website will be automatically moved to the Published bin, and a machine translation will be generated.

autodetectLanguage

Defaults to true.
Automatically set the language to the detected language.
Read about this option in more detail here...

🚧

Overrides Project Setting

This setting overrides the one in the Project Settings: Library Settings.

basePath

This specifies the 'base' or 'root' path of your application. This will be stripped from the URL of the phrase when seen in the "Filter by pages" feature. For example:

  • full URL = https://example.com/one/two/three
  • basePath = https://example.com/one
  • relative path = /two - phrases will be found by Localize in pages starting at this relative path and in any subfolders contained within this folder
  • If not specified, the default value would be https://example.com in the example above.

blockedClasses

An array of CSS class selectors.
When applied, any phrase(s) contained inside an HTML element with the class(es) will not be brought into the Localize dashboard, allowing you to filter out your unwanted content.
Conversely, if you add a class to this list after there is already content in the Localize dashboard, Localize will not display any translations within that HTML element, even if they exist.

blockedClasses: ['admin-mode', 'editing-mode']

blockedIds

An array of CSS ID selectors.
When applied, any phrase(s) contained inside an HTML element with the ID(s) will not be brought into the Localize dashboard, allowing you to filter out your unwanted content.
Conversely, if you add an ID to this list after there is already content in the Localize dashboard, Localize will not display any translations within that HTML element, even if they exist.

defaultLanguage

defaultLanguage: ‘LANG_CODE’
The default language your website will be used when no language has been selected. Defaults to the source language of your website.
You must provide the language code as the value. Language codes can be found here.

disableWidget

Defaults to false.
When true, the default Localize widget is hidden in your web pages (via CSS).

  • Note: This won't remove the widget from the DOM, it simply won't be displayed on the screen.
  • Note: If you have the Widget Customization setting set to NOT display the widget, then setting disableWidget to false still won't display the widget (after all, 2 falses don't make a true!).
  • If you want the widget enabled on some pages but disabled on others, you can use the Localize.showWidget() and Localize.hideWidget() functions. Just be sure to call either of these functions after you've called Localize.initialize().

🚧

Overrides Project Setting

This option overrides the Widget Customization setting in the Project.

localizeImages

Defaults to false.
If true, the image URLs used in your website will appear in your phrases bin to allow for image replacement based on language.

🚧

Overrides Project Setting

This setting overrides the one in the Project Settings: Library Settings.

📘

Subscription Requirement

To use the Image Localization feature you must be subscribed to the Growth Plan or higher.

rememberLanguage

Defaults to false.
If true, Localize will remember the user’s previous language choice and will translate your website to that language.

retranslateOnNewPhrases

Defaults to false.
If set to true, Localize will automatically translate content that is added dynamically to your webpage. For example:

  • If your webpage dynamically adds HTML into the source of the page, our library will translate it once the translations have been generated.
  • Behind the scenes this means the dictionary file with all your translated content is available for use with Localize.translate().
  • However, translations are not generated instantly, so use with our Localize.on() library method with the updatedDictionary event is recommended.
  • When phrases are saved to Localize (either new phrases or deprecated phrases), Localize:
    • ...waits 3.5 seconds, then it checks if the current version of the translation file has been updated since the page originally loaded.
      • If the translation file version has changed since loading the page, the new file is fetched and the page retranslates with the updated translations.
      • Else if the translation file has not changed, then the translation file is not fetched.
    • It repeats the check once more after 6.5 seconds, and fetches the file if it did change.

saveNewPhrases

Defaults to true.
If true, unrecognized phrases will be added to your Localize account. Disable this in development.

saveNewPhrasesFromSource

Defaults to false.
New phrases are only detected when a user is displaying a page in a target language. If true, Localize will detect phrases only when the user is viewing a page in the source language.

🚧

Contact Support

Please contact [email protected] prior to updating this option.

targetLanguage

targetLanguage: ‘LANG_CODE’
Localize will set the target language of your website to the specified language, ignoring the cookie that Localize normally saves in the user's browser.

You must provide the language code as the value. Language codes can be found on your Languages page.

Example Use Case

One possible use case would be: if you are saving the language preference for your users in your website/database, then you can manually set the user's language even if they log in with a totally different computer/device or clear their browser's cache.

<script>
  // Get the user's preferred language from your database.
  var preferredLanguage = 'Language_Code_From_Your_Database';

  Localize.initialize({
    key: '[[app:key]]', 
    targetLanguage: preferredLanguage
    // other options go here, separated by commas
  });

  Localize.on("setLanguage", function(data) {
    var newLanguage = data.to;
    // Save the user's new language preference to your database.
  });
</script>

translateAlt

Defaults to true.
If true, alt attributes within HTML elements will be found by Localize and brought into the dashboard, allowing you to translate them.

translateAriaLabels

Defaults to true.
If true, aria-label attributes within HTML elements will be found by Localize and brought into the dashboard, allowing you to translate them.

Translating aria-labels optimizes your site for use with assistive technologies.

🚧

Overrides Project Setting

This setting overrides the one in the Project Settings: Library Settings.

translateBody

Defaults to true.
If true, Localize will attempt to translate the entire body of the page. If false, Localize will only translate content contained with a "localizejs" class name.

translateClasses

translateClasses: ['example-class1', ‘example-class2’]

Array of class names for which Localize will translate. If you use this option, Localize will ONLY translate content contained in these classes and will ignore all other content in the body of the page.

translateMetaTags

Defaults to true.
If true, metadata tags in the <head> section of the web page will be found by Localize and brought into the dashboard, allowing you to translate them.

Translating metadata tags optimizes your site for SEO. See the list of supported metadata tags here.

🚧

Overrides Project Setting

This setting overrides the one in the Project Settings: Library Settings.

translateNumbers

Defaults to false.
If true, the Localize library will pick up numbers as phrases.
For example: <p>43525234543<p> will be saved as a phrase when set to true.

translateSVGElement

Defaults to true.
If true, text contained within SVGs will be found by Localize and brought into the dashboard, allowing you to translate the text. (SVG files are not supported)

translateTimeElement

Defaults to false.
If true, the Localize library will pick up phrases in <time> elements.
For example: <time>July 7</time> will be saved as a phrase when set to true.

translateTitle

Defaults to true.
If true, the <title> tag of the page in the <head> section of the web page will be translatable.


setLanguage()

Translates the page into the given language.

Localize.setLanguage(languageCode);

The following are the available options for the setLanguage() method.
NOTE: All option names are case-sensitive!!

  • languageCode
    Required. Language codes can be found on your Languages page.

getSourceLanguage()

Returns the language code for the source language of the current project.

var sourceLanguageCode = Localize.getSourceLanguage();

getLanguage()

Returns the language code for the current language of the page. If a language hasn't been set, the language code of the source language is returned.

var currentLanguageCode = Localize.getLanguage();

detectLanguage()

Returns the visitor's list of preferred languages, based on the browser's accept-language header.

Localize.detectLanguage(callback);

The following are the available options for the detectLanguage() method.
NOTE: All option names are case-sensitive!!

  • callback
    Required. A string with the name of the callback function, or the function itself.
Localize.detectLanguage(function(err, languages){
  if (err) return console.log(err);
  console.log(languages)
});

/*
 * Sample output for a browser with English, Spanish and French:
 
 ["en-US", "es", "fr"]
 
 */

getAvailableLanguages()

Returns all available languages for the project.

Localize.getAvailableLanguages(callback);

The following are the available options for the getAvailableLanguages() method.
NOTE: All option names are case-sensitive!!

  • callback
    Required. A string with the name of the callback function, or the function itself.
Localize.getAvailableLanguages(function(err, languages) {
  if (err) return console.log(err);
  console.log(languages)
});

/* 
 * Sample output:
 
 [
   {code: "es", name: "Español"},
   {code: "de", name: "Deutsch"},
   {code: "pt-BR", name: "Português (Brasil)"},
   {code: "zh", name: "中文(简体)"},
   {code: "en", name: "English"}
 ]
 
 */

hideWidget()

Calling this function will hide the widget if it's currently visible.
You can use this function to hide the widget on certain pages.

Localize.hideWidget();

🚧

Overrides Project Setting

Note: Using this function will override the "Display language widget in your website" setting in the Widget settings for the Project.


showWidget()

Calling this function will show the widget if it's currently hidden.

Localize.showWidget();

🚧

Overrides Project Setting

Note: Using this function will override the "Display language widget in your website" setting in the Widget settings for the Project.


translate()

Retrieves the translation for an existing phrase in the currently active language, or adds a new phrase using the contents in the input parameter. Input can be plain text or text within HTML, and can optionally contain variable data.

Localize.translate(input, variables, callback);
Localize.translate(input, callback);  // optionally without variables
Localize.translate(input);  // optionally without variables nor callback

The following are the available options for the translate() method.
NOTE: All option names are case-sensitive!!

input

Required. Can be text, HTML or native DOM elements

variables

Optional. Object of variables that will be replaced in the input, if it's a string

callback

Optional. Callback will trigger once translations have been fetched from Localize.

returns

a string

If the Localize.translate() input is a string, instances of %{variable} will be replaced with the given value in the variables object.

📘

Matching Variable Names

Note that the variable name in the input parameter must match the variable name in the variables parameter, or it will not function correctly.

You may also use HTML <var> tags in the string For example, all of the following variations are supported:

Localize.translate('My name is %{name}', { name: 'Joe' }, callback);
Localize.translate('My name is <var name></var>', { name: 'Joe' }, callback);
Localize.translate('My name is <var name>Joe</var>', callback);

Localize.translate returns:

  • If the active language is the source language of the page, Localize.translate will return the untranslated phrase.
  • If the active language is a target language and the phrase exists and has been translated, Localize.translate will return the translated phrase.
  • If the phrase is a new phrase, Localize.translate will return the untranslated phrase.

Localize.translate can be used with or without a callback. We highly recommend using the callback approach if you're calling Localize.translate in the first 10 seconds of page load to ensure that the latest translations are available. The callback will allow the translation to delay until translations have been fully loaded into the browser. If the translations are already loaded, the callback is executed immediately.

📘

Case Insensitivity

Since all HTML attributes are case insensitive, when defining a <var> name, be advised that the resulting attribute in the returned HTML translation will be converted to all lowercase, for consistency.

For example:
Localize.translate('My name is %{name}', { name: 'Joe' }, callback);

Localize.translate('My name is %{name}', { name: 'Joe' }, function(translation) {
  console.log(translation);
});

📘

Reserved Variable Names

Note that you cannot use any HTML attribute names as variable names, including (but not limited to):
accept, accept-charset, accesskey, action, align, alt, async, autocomplete, autofocus, bgcolor, border, checked, cite, class, color, cols, colspan, disabled, download, href, hreflang, multiple, placeholder, readonly, pluralize, draggable, dropzone, hidden, id, spellcheck, required, reversed, rows, selected, src, style, tabindex, ignore, language


untranslate()

Untranslates a specified element on the page. Use Localize.untranslatePage() if untranslating the whole page.

Localize.untranslate(element);
  • element Required. A DOM node to untranslate

translatePage()

Translates all text on the page

Localize.translatePage();

untranslatePage()

Untranslates all text on the page

Localize.untranslatePage();

prefetch()

Speed up language switching by prefetching translations by language.

Localize.prefetch(languages);
  • languages Required. Accepts a string or an array of languages (ex. 'zh-CN')

phrase()

Saves the phrase, if unrecognized, to your Localize project. Useful for ensuring rarely printed text (ie. an obscure error message) is translated. Returns the phrase it was passed.

Localize.phrase(phrase);
  • phrase Required. A string or an array of strings

on()

Attach an event handler to Localize events.

Localize.on(eventName, fn(data));
  • eventName Required. Name of event to bind to. Can optionally be namespaced: "setLanguage.ns"
  • fn Required. Event handler - receives the event data

Available events:

'initialize'

This event is generated when Localize is initialized.

  • The data object contains the values of any options that were sent in when initializing.
    • key - the Project Key
    • any other options that were set...
Localize.on("initialize", function(data) {
  console.log("initialize: ");
  console.log(data);
});

/*
 * OUTPUT:
initialize:
{…}
key: "[[app:key]]"
rememberLanguage: true
 */

'setLanguage'

This event is generated when the language is switched.

  • The data object contains:
  • from - the old language code
  • to - the new language code
Localize.on("setLanguage", function(data) {
  console.log("setLanguage: from '" + data.from + "' to '" + data.to + "'");
});

/*
 * OUTPUT: 
setLanguage: from 'en' to 'es'
 */

'updatedDictionary'

This event is generated when any changes are made to any phrases in the library in the source or target language.

  • The data object contains:
    • version - the latest version # of the dictionary
    • language - the current target language code
    • dictionary: contains an array of phrase objects in the form:
      • "#source phrase": "target phrase"
Localize.on("updatedDictionary", function(data) {
  console.log("version = " + data.version);
  console.log("language = " + data.language);
  console.log("dictionary = ");
  console.log(data.dictionary);
});

/*
 * OUTPUT: 
version = 790
language = es
dictionary =
{…}
"#Back to Products": "Volver a Productos"
"#About": "Acerca de"
"#Add To Cart": "Añadir a la cesta"
"#Back to Top": "Volver arriba"
...
 */

'widgetLoaded'

This event is generated when the default Localize language switching widget element has fully loaded in the DOM. You can use this event to trigger other events in your code, knowing that the widget is loaded.

Localize.on("widgetLoaded", function() {
  console.log("widgetLoaded = true");
});

/*
 * OUTPUT: 
 * widgetLoaded = true
 */

off()

Remove an event handler.

Localize.off(eventName[, fn]);
  • eventName Required. Name of event to unbind from. Can optionally be namespaced: "setLanguage.ns"
  • fn Optional. The function to unbind from the event.

getExchangeRate()

Returns exchange rate for provided currencies.
Rates are updated hourly.

Localize.getExchangeRate(fromCurrency, toCurrency, callback);
  • fromCurrency Required. The default source currency ID, to be converted from.
  • toCurrency Required. The new currency ID, to be converted to.
  • callback Required. Receives err and rateData arguments.

📘

Currency Codes

The fromCurrency and toCurrency variables expect a 3-letter identifier using the
ISO 4217 Currency Codes.

The following is the JSON schema of the returned rateData.

rateData schema:
  {
     fromCurrency
     toCurrency
     rate
  }

The following is an example that converts $100 US dollars to Euros (value may be different than today's rates).

var dollarsUSD = 100;
var dollarsEUR = null;

Localize.getExchangeRate('USD', 'EUR', function(err, rateData) {
  console.log('Rate data: ', rateData);
  dollarsEUR = dollarsUSD * rateData.rate;
  console.log('Dollars Euro: ', dollarsEUR);
});

// OUTPUT:
Rate data: 
{
  fromCurrency: "USD"
  toCurrency: "EUR"
  rate: 0.896624
}
Dollars Euro: 89.66239999999999

Updated 14 days ago


Frontend API


Configuration options for the on-site Localize script

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.