Documentation

JavaScript

Translate any website with plain JavaScript: add a script tag and mark the text you want to translate. This works with 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:

<script
src="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 npm
npm i @magic-translate/js
# using yarn
yarn 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:

AttributeDescription
data-api-keyRequired. Your Magic Translate API key.
data-languageThe language your content is translated into, for example de. Defaults to the browser's language.
data-source-languageThe language your page is written in. It is detected automatically, so only set it if detection gives wrong results.
data-formalityformal or informal. Not supported for all languages.
data-debugLogs the requests to the console.

createMagicTranslate accepts the corresponding options: apiKey, language, sourceLanguage, formality and debug. It also accepts root to limit translation to a specific element. By default, it translates the whole document.

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>

When you use the script tag, the visitor's language selection is saved for the next page load.

Example project

You can find an example project on GitHub and see it live.