Documentation

JavaScript API

Besides translating your page, the Magic Translate client can be used from your own scripts.

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.

The current language

magicTranslate.language is the current language. setLanguage changes it and translates the page again, and onLanguageChange calls you back when it 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();