JavaScript
How to use Magic Translate on any website with plain JavaScript. Add one script tag, mark your text, and it is translated. This works for plain HTML, server-rendered pages, WordPress and other CMSs, and apps built with any framework.
Setup with a script tag
Add the Magic Translate script to your page:
<scriptsrc="https://cdn.jsdelivr.net/npm/@magic-translate/js@1/dist/magic-translate.min.js"data-api-key="<your-api-key>"data-language="de"defer></script>
If you don't have an API key yet, sign up for Magic Translate to get one. Since the key is part of your page, limit it to your own domains under allowed domains.
Then put the text you want to translate in a <t> element:
<h1><t>Please translate me!</t></h1>
That's it. Your website can now be translated into over 70 languages.
Leave out data-language to translate into the language of the visitor's browser.
Setup with npm
If you bundle your JavaScript, install the client from npm instead:
# using npmnpm i @magic-translate/js# using yarnyarn add @magic-translate/js
import { createMagicTranslate, Language } from '@magic-translate/js';const magicTranslate = createMagicTranslate({apiKey: '<your-api-key>',language: Language.DE // any supported language});
createMagicTranslate starts translating the page right away.
Configuration
The script tag accepts these attributes:
| Attribute | Description |
|---|---|
data-api-key | Required. Your Magic Translate API key. |
data-language | The language your content is translated into, for example de. Defaults to the browser's language. |
data-source-language | The language your page is written in. It is detected automatically, so only set it if detection gives wrong results. |
data-formality | formal or informal. Not supported for all languages. |
data-debug | Logs the requests to the console. |
createMagicTranslate takes the same settings as apiKey, language, sourceLanguage, formality and debug, plus root: the element whose content is translated, which is the whole document by default.
Changing languages
Call setLanguage to translate the page into another language. With the script tag, the instance is available as window.magicTranslate:
<select onchange="magicTranslate.setLanguage(this.value)"><option value="en">English</option><option value="de">Deutsch</option><option value="fr">FranΓ§ais</option></select>
With the script tag, the language picked last is remembered on the next page load.