Skip to main content
JavaScript API

Learn about the JavaScript API for Transifex Live

Nina Eleftheriadou avatar
Written by Nina Eleftheriadou
Updated over a week ago

The JavaScript API lets you change the normal behavior of the Transifex Live snippet for specific use cases. Use the API to customize the language selector, define the language detection on the user's side, enable the automatic detection of phrases, and mark what's translatable and detectable.

๐Ÿ“ Note: The window.liveSettings parameters are typically controlled remotely within Transifex Live Tool, and every parameter set in JavaScript API will override those.

Transifex Live works following this loading process:

  • Read the window.liveSettings options.

  • Parse the static content.

  • Fetch the available languages.

  • Translate a page (if the selected language is not the source language).

  • Store the translations in local storage.


Transifex Live JavaScript code

The liveSettings object contains parameters that define how Transifex Live behaves, including language detection and language picker settings.

This object supports the following structure in general:

window.liveSettings = {
api_key: "<key>",
detectlang: true|false|function() { return lang-code; },
picker: "top-left|top-right|bottom-left|bottom-right|#id",
version: 'latest|<version>',
autocollect: true|false,
dynamic: true|false,
staging: true|false,
xss_protect: true|false,
parse_attr: ["attr1", "attr2", ...],
ignore_tags: ["tag1", "tag2", ...],
ignore_class: ["classname1", "classname2"],
manual_init: true|false,
translate_urls: true|false
};

Only the api_key parameter is mandatory. The rest of the fields are optional and can be set up as described below.

Language detection

The detectlang property is used to define the initial target language of the user.

Values are:

  • true to enable auto-detection.

  • false to disable auto-detection (default).

  • function for user-defined logic.

Example:

window.liveSettings = {
...
detectlang: function() {
//return language code
return 'fr';
},
...
}

Auto-detection follows the pattern described here.

Language selector

The picker property is an easy way to construct a language selector so that you can switch between languages. It accepts the following options:

  • top-left

  • top-right

  • bottom-left

  • bottom-right

  • element id

The first four options will create a floating selector in the corner of the page. It should be used for debugging as each website should define its own style for changing languages.

The element id option will create a select element as a child to the defined element id.

For example:

<select id="tx-live-lang-picker">
<option value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
</select>

If you decide to move forward with the last option, please keep in mind that you need to customize the appearance of the language picker.

The automatic language selector is fine for getting started, but in practice, each website has its own needs. In that case, it's best to use the JavaScript API to create a custom language selector using the following example.

Working with staging servers

Sometimes, preparing your translations on a staging/test server is helpful before taking them live to a production server. By default, Transifex Live automatically identifies a staging environment from production. You can override this by setting the staging: true option (off by default) on the JavaScript snippet you install on a staging server.

Setting this option has the following effect:

  • Automatically detected and collected strings are marked as staging.

  • The website is translated using translations taken live by clicking Publish to staging in Transifex Live.

Versions

With the version property, you can define a specific version of your content to be deployed.

This functionality is to be enabled in the future.

Given that translations might contain HTML code, you can opt-in to an additional layer of security by enabling XSS protection on the client side. Setting the xss_protect: true option (off by default) in the JavaScript snippet will sanitize HTML translations before adding them to the DOM.

This is not enabled by default because the sanitization process might strip some intended custom logic or custom HTML attributes in translations. We would suggest testing and making sure the website is functional before enabling this flag on production.

Manual initiation for running the JavaScript snippet

The JavaScript snippet should, ideally, be placed in the Header. Nothing else needs to be done if this is the case. However, if that isn't possible, you should set the manual_init parameter to true and then call Transifex.live.init() when you're ready for the JavaScript snippet to run.

Track dynamic updates in HTML tag attributes

Setting the translate_urls property to true (it is false by default) will allow Transifex Live to automatically detect dynamic changes to attributes similar to how the handling dynamic content functionality works.


Callbacks

Transifex Live API is making use of the Transifex.live.* namespace and is asynchronous. Callbacks can be registered to capture several Transifex Live events.

onReady

This is called when Transifex Live has been loaded and the translation applied to the page. Think of it as the jQuery $(document).ready equivalent.

Transifex.live.onReady(function(load_msec) {

});

The load_msec-parameter can be used to benchmark the milliseconds overhead of the Transifex Live operations.

onFetchLanguages

This event is triggered when the available languages have been downloaded from the Transifex CDN.

Transifex.live.onFetchLanguages(function(languages) {

});

The callback takes as a parameter an array that describes the languages, for example:

languages = [
{
name: 'English',
code: 'en',
source: true
},
{
name: 'German',
code: 'de'
},
{
name: 'Greek',
code: 'el'
}
]

onTranslatePage

When a page is translated into a language, the following callback is triggered:

Transifex.live.onTranslatePage(function(language_code) {

});

The language_code-parameter defines the language the page was translated into.

onDynamicContent

This callback is triggered when dynamic content is detected automatically or the Transifex.live.translateNode or Transifex.live.translateNodes API calls are invoked.

Transifex.live.onDynamicContent(function(new_strings) {

});

onError

Called when an error has occurred, e.g., translations failed to download.

Transifex.live.onError(function(err) {

});

unBind

Unbind a function from callbacks.

function cb(lang) {
...
}
Transifex.live.onTranslatePage(cb);
...
Transifex.live.unBind(cb);


Methods

A set of methods is available after the onReady-callback has been triggered.

hasLanguageCode

Check if a language code exists.

true|false = Transifex.live.hasLanguageCode(lang_code)

hasTargetLanguage

Check if the target (translation) language code exists.

true|false = Transifex.live.hasTargetLanguage(lang_code)

getSourceLanguage

Get source language.

{code:<code>, name:<name>} = Transifex.live.getSourceLanguage()

getLanguageName

Get language name by language code.

name = Transifex.live.getLanguageName(lang_code)

getAllLanguages

Get all languages.

{...} = Transifex.live.getAllLanguages()

Please take a look at Transifex.live.onFetchLanguages for the object returned.

matchLanguageCode

Check if a language code has a fuzzy match. For example, 'de' and 'de_DE' or 'de-de' will be the same. Return a target or source language code that matches the search.

lang_code = Transifex.live.matchLanguageCode(lang_code)

normalizeLangCode

Normalize language code to match the xx_YY@ZZ pattern.

For example, convert de-de to de_DE.

lang_code = Transifex.live.normalizeLangCode(lang_code)

detectLanguage

Try to detect the user's language based on the browser URL or preferred languages.

lang_code = Transifex.live.detectLanguage()

getSelectedLanguageCode

Get the currently selected language code.

lang_code = Transifex.live.getSelectedLanguageCode()

translateTo

Trigger a page to be translated to the defined language code.

Transifex.live.translateTo("fr")


translateNode

Manually translate additional dynamic content by specifying a parent node. New strings are also auto-collected if the automatic collection is enabled.

Transifex.live.translateNode(element)

e.g., with jQuery:

Transifex.live.translateNode($('#id').get(0));

translateNodes

Manually translate an array of parent nodes. New strings are also auto-collected if the automatic collection is enabled.

Transifex.live.translateNodes(array)

translateText

Manually translate a text fragment. Strings are also auto-collected if the automatic collection is enabled.

Dynamic variables are also populated using an (optional) variable object.

var translation = Transifex.live.translateText(
"Hello {username}",
{
username: "John"
}
);

Please take a look at the example of using this function with dynamic content.


๐Ÿ’กTip

Looking for more help? Get support from our Transifex Community Forum!

Find answers or post to get help from Transifex Support and our Community.

Did this answer your question?