Frontend API
Configuration options for the on-site Localize script
Check out the Quickstart for Web 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. Below that are the available options you can set to tailor your experience with Localize, to better suit your localization workflows.
<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>
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.
allowInlineBreakTags
Defaults to false
.
If true
, whenever you have a <BR>
element in your content, Localize will not break up the parent element's content but instead will keep all sibling child elements together in the parent or containing element.
Example:
With the allowInlineBreakTags
set to false
, the source phrase:
<div>
Hello George! How was your first day as a CIT?<br>
I hope it wasn't too <span style="color: red">hot</span> for you!
</div>
...will be brought into your dashboard as the following phrases:
- Hello George! How was your first day as a CIT?
- I hope it wasn't too
- {{1}}hot{{/1}}
- for you!
With the allowInlineBreakTags
set to true
, the source phrase above will be brought into your dashboard as the following phrase:
- Hello George! How was your first day as a {{1}}CIT{{/1}}?{{2}}{{/2}} I hope it wasn't too {{3}}hot{{/3}} for you!
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 one of the ID(s) will not be brought into the Localize dashboard, allowing you to filter out your unwanted content.
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’
Localize will set the initial language on your website to LANG_CODE
. Language codes can be found here.
Defaults to the source language of your website.
Overrides Browser Language Choice
Note that if you set the
defaultLanguage
option, this will override any language preference that the user has set in their browser.
disableWidget
Defaults to false
.
When true
, the default Localize language-switching widget is hidden in your web pages (via CSS).
- Note: This won't remove the widget from the DOM, it just hides it from view.
- Note: If you have the Widget Customization setting set to NOT display the widget, then setting
disableWidget
tofalse
still won't display the widget (after all, 2false
s don't make atrue
!). - 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.
enabledLanguages
An array of language codes that determine which target languages should be shown on the default Localize language-switching widget.
enabledLanguages: ['es', 'fr'],
In the example above, only Spanish (es) and French (fr) will be shown on the language-switching widget. This option allows you to programmatically set the available languages on a page or user basis, depending on your needs.
Language codes can be found here.
Example Use Case: Customer-based Languages
As a SaaS company that offers translations to our customers, we want to be able to customize the list of languages on a per-customer basis, so our customers only see the languages they need.
You can store the list of languages per customer in the company profile in your database, then use that list of languages when Localize is initialized for that customer.
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.
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.
- ...waits 3.5 seconds, then it checks if the current version of the translation file has been updated since the page originally loaded.
saveNewPhrases
Defaults to true
.
If true
, unrecognized phrases will be added to your Localize account.
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 translate the contents in the entire <body>
element of the page.
If false
, Localize will only translate the content within an HTML element(s) that contains the attribute class="localizejs"
or id="localizejs"
.
translateClasses
translateClasses: ['example-class1', ‘example-class2’]
An 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.
useSubdirectoriesWithWidget
Defaults to false
.
If true
, when a target language is selected in the default Localize language-switching widget, the system will add the appropriate language code to the current page's URL. See the example for the "contact-us" page in the following table.
Language | Language Code | URL |
---|---|---|
English (source) | en | example.com/contact-us |
French | fr | example.com/fr/contact-us |
Spanish | es | example.com/es/contact-us |
useSubdomainsWithWidget
Defaults to false
.
If true
, when a target language is selected in the default Localize language-switching widget, the system will add the appropriate language code to the current page's URL. See the example for the "contact-us" page in the following table.
Language | Language Code | URL |
---|---|---|
English (source) | en | example.com/contact-us |
French | fr | fr.example.com/contact-us |
Spanish | es | es.example.com/contact-us |
vueSafe
Defaults to false
.
Set this to true
if you are working on a website that uses the Vue.js framework to build your website to avoid DOM-based conflicts.
In general, if you are having problems when using Localize on your site and see an error in the console that states "Cannot remove a child from a different parent", then you may also need to set this option to true
even if you are not working on a Vue.js-based website.
- One example is if you are localizing a Salesforce Digital Experience app.
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 default Localize language-switching 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 default Localize language-switching 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.
hideLanguagesInWidget()
Call this method to remove languages from the Localize default language-switching widget.
Sometimes, you may want to display a different set of languages in the widget on different pages of your website or for different customers using your SaaS tool or when you are working on the translations for a language. Call this method with the list of target language codes you'd like to hide in the widget. Note: the source language will always be included in the widget.
document.addEventListener("DOMContentLoaded", function() {
Localize.hideLanguagesInWidget(['de', 'fr']);
});
setWidgetLanguages()
Call this method to set the languages you'd like to have active in the Localize default language-switching widget.
Sometimes, you may want to display a different set of languages in the widget on different pages of your website or for different customers using your SaaS tool. Call this method with the list of target language codes that you'd like to make available in the widget. Note: the source language will always be included in the widget.
document.addEventListener("DOMContentLoaded", function() {
Localize.setWidgetLanguages(['es', 'fr']);
});
translate()
Retrieves the translation for an existing source phrase in the currently active language, or adds a new source 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 parameters for the translate() method.
NOTE: All parameter names are case-sensitive!!
- input
Required. Can be text, HTML, or native DOM elements
This is a phrase in the source language. This method only translates content from the source language into any of your target languages.
- variables
Optional. An object with key:value
pairs of variables that will be replaced in the input parameter.
- callback
Optional. The callback function will trigger once translations have been fetched from Localize.
- returns
a string
If the Localize.translate()
input
parameter 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 thevariables
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);
Retrieving translations via a CSS class name
If you are looking to retrieve the translation of a DOM node via a CSS class name, you'll have to provide an index to the array that will be returned since there can be more than 1 instance of a node with that CSS class on the page. Localize cannot return the entire array of nodes that match the CSS class.
Localize.translate(document.getElementsByClassName('foo')[1]);
or
Localize.translate($('foo')[1]);
Localize.translate()
returns:
- If the active language is the source language of the page,
Localize.translate
will return the untranslated phrase, adding the phrase to your dashboard if it didn't previously exist. - 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 and add it to your dashboard.
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 be delayed 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()
Returns the DOM node (or nodes) within the <body>
tag that was (were) translated, based on your initialization settings, using the currently selected language. For example:
- If you are using the standard initialization settings, it will return the entire
<body>
node, translated to the currently selected language. - If you have
translateBody
set to false, it will only return nodes that have the CSS class or id oflocalizejs
.
Note: This pulls the translations from the published phrases in your project and replaces the source content with those translations. It does not automatically translate new phrases. (Use the translateImmediate() method for that.) If new phrases are found on the page they will be added to your Localize dashboard as new phrases.
Localize.translatePage();
untranslatePage()
Untranslates all text on the page and switches the language back to the source language.
Localize.untranslatePage();
translateImmediate()
Provides an immediate translation of the given phrase.
One possible use case for using this method is to support searching in a target language.
Localize.translateImmediate(targetLanguage, phrase, callback)
The following are the parameters for the translateImmediate() method.
NOTE: All parameter names are case-sensitive!!
- targetLanguage
Required. This is the language code for the language into which you want to translate the given phrase
.
The source language is assumed to be the currently selected language on the website.
- phrase
Required. The phrase that you'd like to translate.
- callback
Required. A callback function that accepts an error
and a result
parameter.
The following details what the method does to retrieve or create the translation.
- If you are translating from a target language to the source language of your project:
- ...it first looks to see if the phrase already exists in your project and if it does it returns the existing source language phrase.
- ...it then looks at the Glossary and if the phrase matches a glossary term it returns the source language version of the matching term.
- ...otherwise, it generates a machine translation for the phrase and returns it.
- The given
phrase
is not added to your dashboard, it is a one-time use translation.
- The given
- If you are translating between target languages it will generate a machine translation for the phrase and return it.
- The given phrase is not added to your dashboard, it is a one-time use translation.
Using these details you may be able to better "train" the method to use preexisting content in your dashboard.
Localize.translateImmediate('en', 'mejores sofás blancos', function(err, result) {
console.log('err: ', err, 'result: ', result);
});
/* Output:
err: null
result:
phrase: "mejores sofás blancos"
targetLanguage: "en"
translation: "best white sofas"
*/
Subscription-Specific
This feature is not available on all subscription plans. Please contact your Account Executive or Customer Success Manager for details.
prefetch()
Speed up language switching by prefetching translations by language.
Localize.prefetch(languages);
languages
Required. Accepts a string or an array of language codes (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...
NOTE: Be sure to put this call before your initialize()
call so that it is ready to listen for the initialize event.
Localize.on("initialize", function(data) {
console.log("initialize: ");
console.log(data);
});
Localize.initialize({
key: '[[app:key]]',
rememberLanguage: true,
// other options go here, separated by commas
});
/*
* 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
*/
'error'
This event is generated when there is an error when initializing the library.
- The error string will describe the error that occurred.
Localize.on('error', function(error) {
console.log("Oh No! You just got this error: " + error)
});
/*
* OUTPUT:
* Oh No! You just got this error: Invalid Project Key
*/
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.
number()
Convert the format of a number to the format used in the currently selected language/locale.
Localize.number(originalValue, callback);
originalValue
Required (Number). The original numerical value that you want to convert.callback
Required. Receiveserr
andvalue
arguments.
Localize.number(123456.789, function(err, value) {
console.log('convertedNumber = ' + value);
});
// Output with Spanish set as the current language:
convertedNumber = 123.456,789
currency()
Convert a monetary value from one currency to another, using the current exchange rate.
Rates are updated hourly.
Localize.currency(originalValue, { originalCurrency: fromCurrency, targetCurrency: toCurrency }, callback);
originalValue
Required (Number). The original monetary value that you want to convert.fromCurrency
Required (String). The default source currency code, to be converted from.toCurrency
Required (String). The new currency code, to be converted to.callback
Required. Receiveserr
andvalue
arguments.
Currency Codes
The fromCurrency and toCurrency variables expect a 3-letter identifier using the
ISO 4217 Currency Codes.
Localize.currency(1234.56, { originalCurrency: "USD", targetCurrency: "CAD" }, function (err, value) {
console.log('Converted value = ' + value + ' CAD');
});
// OUTPUT:
Converted value = 1573.62 CAD
getExchangeRate()
Returns the exchange rate between the provided currencies.
Rates are updated hourly.
Localize.getExchangeRate(fromCurrency, toCurrency, callback);
fromCurrency
Required. The default source currency code, to be converted from.toCurrency
Required. The new currency code, to be converted to.callback
Required. Receiveserr
andrateData
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 3 months ago