Documentation

JavaScript API

You can also use the Magic Translate client directly in your scripts to translate strings and change the language.

Getting the instance

With the script tag, the instance is created once the page has loaded and is available as window.magicTranslate. To use it as soon as it is ready, listen for the magictranslate:ready event:

document.addEventListener('magictranslate:ready', (event) => {
const magicTranslate = event.detail;
});

With npm, createMagicTranslate returns the instance.

Translating in code

To translate a string, call translate. It returns a promise.

const message = await magicTranslate.translate('Your order has been placed');
// with options
const formal = await magicTranslate.translate('How are you?', {
lang: 'fr',
formality: 'formal'
});

Without the lang option, the text is translated into the current language. With an id, you can edit this use of the text on its own.

Values that should not be translated go in v, referenced as $name. The text is translated once as a template and cached, whatever the values are:

const message = await magicTranslate.translate('Your order $id has shipped', {
v: { id: order.id }
});

The current language

Read the current language with magicTranslate.language. Use setLanguage to change it and translate the page again, or onLanguageChange to run a callback whenever the language changes:

magicTranslate.setLanguage('fr');
const unsubscribe = magicTranslate.onLanguageChange((language) => {
document.documentElement.lang = language;
});

Stopping

destroy stops translating the page. Content that is already translated stays translated.

magicTranslate.destroy();