Skip to main content

Webpage translation JSSDK

Description

A page translation plugin powered by a large translation model that provides webpage translation. With the JSSDK, you can add multilingual support to your website in one click.

How it works

image

Integrate the JSSDK

Current version

Item

Value

Version

3.0.1

CDN root path

https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/

The examples in this document use version 3.0.1. When you upgrade, replace the version number in the CDN links accordingly.
The SDK provides two translation modes:
  • Page translation (pageTranslate): directly replaces the source text on the page with the translation, ideal for monolingual display.
  • Side-by-side paragraph translation (paragraphTranslate): inserts the translation after the source text, ideal for reading the source text and translation side by side.
It also supports:
  • Lazy-load translation (only translates the visible area)
  • Dynamic content translation (automatically translates after DOM changes)
  • Glossaries and translation memory
  • Fine-grained hooks (insert custom logic before and after translation)

Installation

Load the SDK from the CDN with a script tag. Two methods are supported: Include index.js once (it contains the core and all plugins) to use both page translation and side-by-side translation:

File

Description

URL

index.js

Full bundle (core + plugins)

https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/index.js

<script src="https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/index.js"></script>

Method 2: On-demand imports

Load core.js first, then load the plugin scripts you need:

File

Description

URL

core.js

Core SDK

https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/core.js

page.js

Page translation plugin

https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/page.js

paragraph.js

Side-by-side translation plugin

https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/paragraph.js

<!-- 页面翻译 -->
<script src="https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/core.js"></script>
<script src="https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/page.js"></script>

<!-- 段落对照:将 page.js 换成 paragraph.js -->
<!-- 两种模式都要用:同时引入 page.js 与 paragraph.js -->
Notes:
  • The full bundle requires only one file. With on-demand imports, load core.js first, then the plugins.
  • The global object is window.AliTranslate, with the alias window.__AliTranslate (both refer to the same instance).

Quick start

Page translation (Pure Page)

<script src="https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/index.js"></script>
<script>
  AliTranslate.pageTranslate({
    getToken: async (params) => {
      const res = await fetch('https://your-sign-api.example.com/signature', {
        method: 'POST',
        body: JSON.stringify(params),
      });
      return (await res.json()).data;
    },
    srcLanguage: 'auto',
    tgtLanguage: 'en',
    targetSelectors: ['#app'],
    excludeSelectors: ['.no-translate', 'code', 'pre'],
    translateAttributes: ['placeholder'],
    lazyload: true,
    dynamic: true,
  });
</script>

Side-by-side paragraph translation (Paragraph Compare)

<script src="https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/index.js"></script>
<script>
  AliTranslate.paragraphTranslate({
    getToken: async (params) => {
      const res = await fetch('https://your-sign-api.example.com/signature', {
        method: 'POST',
        body: JSON.stringify(params),
      });
      return (await res.json()).data;
    },
    srcLanguage: 'auto',
    tgtLanguage: 'en',
    targetSelectors: ['#article'],
    excludeSelectors: ['.no-translate', 'code', 'pre'],
    translateAttributes: ['placeholder'],
    lazyload: true,
    dynamic: true,
    extraBlockSelectors: ['.article-title', 'h1', 'h2', 'h3'],
    extraInlineSelectors: ['.breadcrumb', '.tag-inline'],
  });
</script>

SDK configuration parameters (SDKConfig)

The following SDK-level parameters are shared by AliTranslate.pageTranslate / AliTranslate.paragraphTranslate:

Parameter

Type

Required

Description

getToken

(params) => Promise<SignedRequest>

Yes

Authentication signing function that returns a signed request ready to call the translation service

terminologies

Array<{ src, tgt }>

No

Glossary that improves the consistency of domain terms

examples

Array<{ src, tgt }>

No

Translation memory

domainHint

string

No

Business domain (passed through to the translation request)

chunkSize

number

No

Chunk size threshold (affects request batching and throughput)

maxRetries

number

No

Maximum number of retries after a translation failure

afterTranslate

(result) => void

No

Callback invoked when translation is complete


PageTranslateConfig parameters

Parameter

Type

Required

Description

tgtLanguage

LANGUAGE

Yes

Target language

srcLanguage

LANGUAGE

No

Source language. If not specified, the language is automatically detected.

targetSelectors

string | string[]

No

Translation root node. The default value is body.

excludeSelectors

string | string[]

No

Excluded nodes (once matched, the entire subtree is not translated)

translateAttributes

string | string[]

No

Element attributes that support translation

lazyload

boolean

No

Whether to enable lazy-load translation

lazyOffset

number

No

Viewport offset for lazy loading (px)

lazySelectors

string | string[]

No

Lazy translation selectors (reserved field in the current version; prefer targetSelectors)

dynamic

boolean

No

Whether to watch for DOM changes and translate automatically

translateDelay

number

No

Initialization wait / dynamic translation throttle delay (ms)

rules

Array<{ selector; style?; className? }>

No

Page translation rules (applied to the source text container)

onBeforeInsertTrans

(ctx) => void | HTMLElement | Promise<...>

No

Callback invoked before the translation is inserted

onTranslatingStart

(ctx) => void | Promise<void>

No

Callback invoked when translation of a node starts

onTranslatingEnd

(ctx) => void | Promise<void>

No

Callback invoked when translation of a node ends


ParagraphTranslateConfig parameters

Parameter

Type

Required

Description

tgtLanguage

LANGUAGE

Yes

Target language

srcLanguage

LANGUAGE

No

Source language. If not specified, the language is automatically detected.

targetSelectors

string | string[]

No

Translation root node. The default value is body.

excludeSelectors

string | string[]

No

Excluded nodes (once matched, not included in paragraph extraction)

translateAttributes

string | string[]

No

Element attributes that support translation

lazyload

boolean

No

Whether to enable lazy-load translation

lazyOffset

number

No

Viewport offset for lazy loading (px)

lazySelectors

string | string[]

No

Lazy translation selectors (reserved field in the current version; prefer targetSelectors)

dynamic

boolean

No

Whether to watch for DOM changes and translate automatically

translateDelay

number

No

Initialization wait / dynamic translation throttle delay (ms)

extraBlockSelectors

string | string[]

No

Forces translations to be inserted as blocks (on their own line)

extraInlineSelectors

string | string[]

No

Forces translations to be inserted inline (on the same line)

rules

TransStyleRule[]

No

Style rules for side-by-side translation

onBeforeInsertTrans

(ctx) => void | HTMLElement | Promise<...>

No

Callback invoked before <trans> is inserted

onTranslatingStart

(ctx) => void | Promise<void>

No

Callback invoked when translation of a paragraph starts

onTranslatingEnd

(ctx) => void | Promise<void>

No

Callback invoked when translation of a paragraph ends

TransStyleRule

interface TransStyleRule {
  selector: string
  transStyle?: Record<string, string> // 作用于译文节点 <trans>
  style?: Record<string, string>      // 作用于命中 selector 的父容器
  className?: string                  // 作用于命中 selector 的父容器
}

Hooks and rollback-safe DOM changes

The SDK provides a mutator (a reversible change operator) for safe DOM operations in hooks. Changes made through it are automatically rolled back when removeTranslations() is called.
<script src="https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/index.js"></script>
<script>
  AliTranslate.paragraphTranslate({
    getToken: async (params) => {
      const res = await fetch('https://your-sign-api.example.com/signature', {
        method: 'POST',
        body: JSON.stringify(params),
      });
      return (await res.json()).data;
    },
    tgtLanguage: 'en',
    onTranslatingStart: (ctx) => {
      const loading = document.createElement('span');
      loading.className = 'loading';
      loading.textContent = '翻译中...';
      loading.setAttribute('data-source-hash', ctx.sourceHash);
      ctx.mutator.appendNode(ctx.paragraph.commonAncestor, loading);
    },
    onTranslatingEnd: (ctx) => {
      const loading = ctx.paragraph.commonAncestor.querySelector(
        `.loading[data-source-hash="${ctx.sourceHash}"]`,
      );
      if (loading) ctx.mutator.removeNode(loading);
    },
    onBeforeInsertTrans: (ctx) => {
      ctx.transNode.style.color = '#4f46e5';
      return ctx.transNode;
    },
  });
</script>
The mutator capabilities:
  • setStyle(el, prop, value, priority?)
  • addClass(el, className)
  • removeClass(el, className)
  • appendNode(parent, node)
  • removeNode(node)

Languages and enum values

Common language values:
  • auto (automatic detection)
  • zh, en, ja, ko, fr, de, es, ru, ar, th, vi
For the complete language enumeration, see the LANGUAGE type definition in the SDK.

Common APIs

// 移除翻译结果(保留 SDK 实例)
AliTranslate.removeTranslations()

// 销毁 SDK(释放资源,插件与事件解绑)
AliTranslate.destroy()

Full example (side-by-side translation + rules + hooks)

<script src="https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/index.js"></script>
<script>
  AliTranslate.paragraphTranslate({
    getToken: async (params) => {
      const res = await fetch('https://your-sign-api.example.com/signature', {
        method: 'POST',
        body: JSON.stringify(params),
      });
      return (await res.json()).data;
    },
    srcLanguage: 'auto',
    tgtLanguage: 'en',
    targetSelectors: ['#article'],
    excludeSelectors: ['.no-translate', 'code', 'pre'],
    lazyload: true,
    lazyOffset: 120,
    dynamic: true,
    translateDelay: 200,
    extraBlockSelectors: ['.title', 'h1', 'h2'],
    extraInlineSelectors: ['.breadcrumb'],
    rules: [
      {
        selector: '.highlight',
        transStyle: { color: '#4f46e5' },
        style: { background: '#eef2ff' },
        className: 'translated-highlight',
      },
    ],
    onBeforeInsertTrans: (ctx) => {
      // 自定义译文节点样式,给所有翻译前(排除h1, h2, h3)添加一个border
      if (ctx.paragraph.commonAncestor.matches('h1, h2, h3')) {
        return ctx.transNode;
      }
      ctx.transNode.style.borderLeft = '2px solid #e94560';
      ctx.transNode.style.paddingLeft = '0.75rem';
      ctx.transNode.style.marginTop = '0.5rem';
    },
    onTranslatingStart: (ctx) => {
      // 为翻译中的节点添加 loading
      const loading = document.createElement('span');
      loading.className = 'loading';
      loading.setAttribute('data-source-hash', ctx.sourceHash);
      loading.textContent = '翻译中...';
      ctx.mutator.appendNode(ctx.paragraph.commonAncestor, loading);
    },
    onTranslatingEnd: (ctx) => {
      // 移除自定义添加的 loading
      const root = ctx.paragraph.commonAncestor;
      const loading = root.querySelector(`.loading[data-source-hash="${ctx.sourceHash}"]`);
      if (loading) ctx.mutator.removeNode(loading);
    },
  });
</script>

To support both page translation and side-by-side paragraph translation, we recommend using the full index.js bundle and clearly separating the switching and cleanup flows of the two modes in your business UI.

Implement a token service

Sign requests using the V3 request body & signature mechanism of the Alibaba Cloud SDK.
javascript
// 通过calculateSignature方法生成签名
import * as crypto from 'crypto';
export interface SignatureRequest {
  httpMethod: string;
  canonicalUri: string;
  host: string;
  xAcsAction: string;
  xAcsVersion: string;
  headers: Record<string, string>;
  body: any;
  queryParam: Record<string, any>;
}
export interface BatchTranslateRequest {
  scene: string;
  sourceLanguage: string;
  streaming: boolean;
  targetLanguage: string;
  text: { [key: string]: string };
}
export class Request implements SignatureRequest {
  httpMethod: string;
  canonicalUri: string;
  host: string;
  xAcsAction: string;
  xAcsVersion: string;
  headers: Record<string, string>;
  body: any;
  queryParam: Record<string, any>;
  constructor(httpMethod: string, canonicalUri: string, host: string, xAcsAction: string, xAcsVersion: string) {
    this.httpMethod = httpMethod;
    this.canonicalUri = canonicalUri || '/';
    this.host = host;
    this.xAcsAction = xAcsAction;
    this.xAcsVersion = xAcsVersion;
    this.headers = {};
    this.body = null;
    this.queryParam = {};
    this.initHeader();
  }
  private initHeader() {
    const date = new Date();
    this.headers = {
      'host': this.host,
      'x-acs-action': this.xAcsAction,
      'x-acs-version': this.xAcsVersion,
      'x-acs-date': date.toISOString().replace(/\..+/, 'Z'),
      'x-acs-signature-nonce': crypto.randomBytes(16).toString('hex')
    }
  }
}
const ALGORITHM = 'ACS3-HMAC-SHA256';
const accessKeyId = process.env.ACCESS_KEY_ID; // 这里填入阿里云的AK
const accessKeySecret = process.env.ACCESS_KEY_SECRET; // 这里填入阿里云的SK
const workspaceId = process.env.WORKSPACE_ID; // 这里填入百炼的WorkspaceId
const encoder = new TextEncoder();
const httpMethod = 'POST';
const canonicalUri = '/anytrans/translate/batchForHtml';
const xAcsAction = 'BatchTranslateForHtml';
const xAcsVersion = '2025-07-07';
const host = 'anytrans.cn-beijing.aliyuncs.com';
export interface SignedRequest {
  url: string;
  method: string;
  host: string;
  headers: Record<string, string>;
  body?: any; // 可能是 Uint8Array 或 Base64 字符串
}
export function getAuthorization(signRequest: SignatureRequest): SignedRequest {
  try {
    const newQueryParam: Record<string, any> = {};
    processObject(newQueryParam, "", signRequest.queryParam);
    signRequest.queryParam = newQueryParam;
    // 步骤 1:拼接规范请求串
    const canonicalQueryString = Object.entries(signRequest.queryParam)
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([key, value]) => `${percentCode(key)}=${percentCode(value)}`)
      .join('&');
    // 请求体,当请求正文为空时,比如GET请求,RequestPayload固定为空字符串
    const requestPayload = signRequest.body || encoder.encode('');
    const hashedRequestPayload = sha256Hex(requestPayload);
    signRequest.headers['x-acs-content-sha256'] = hashedRequestPayload;
    // 将所有key都转换为小写
    signRequest.headers = Object.fromEntries(
      Object.entries(signRequest.headers).map(([key, value]) => [key.toLowerCase(), value])
    );
    const sortedKeys = Object.keys(signRequest.headers)
      .filter(key => key.startsWith('x-acs-') || key === 'host' || key === 'content-type')
      .sort();
    // 已签名消息头列表,多个请求头名称(小写)按首字母升序排列并以英文分号(;)分隔
    const signedHeaders = sortedKeys.join(";")
    // 构造请求头,多个规范化消息头,按照消息头名称(小写)的字符代码顺序以升序排列后拼接在一起
    const canonicalHeaders = sortedKeys.map(key => `${key}:${signRequest.headers[key]}`).join('\n') + '\n';
    const canonicalRequest = [
      signRequest.httpMethod,
      signRequest.canonicalUri,
      canonicalQueryString,
      canonicalHeaders,
      signedHeaders,
      hashedRequestPayload
    ].join('\n');
    console.log('canonicalRequest=========>\n', canonicalRequest);
    // 步骤 2:拼接待签名字符串
    const hashedCanonicalRequest = sha256Hex(encoder.encode(canonicalRequest));
    const stringToSign = `${ALGORITHM}\n${hashedCanonicalRequest}`;
    console.log('stringToSign=========>', stringToSign);
    // 步骤 3:计算签名
    const signature = hmac256(accessKeySecret!, stringToSign);
    console.log('signature=YOUR_SIGNATURE>', signature);
    // 步骤 4:拼接 Authorization
    const authorization = `${ALGORITHM} Credential=${accessKeyId},SignedHeaders=${signedHeaders},Signature=YOUR_SIGNATURE
    console.log('authorization=========>', authorization);
    signRequest.headers['Authorization'] = authorization;
    // 构建完整的URL
    let url = `https://${signRequest.host}${signRequest.canonicalUri}`;
    if (signRequest.queryParam && Object.keys(signRequest.queryParam).length > 0) {
      const query = new URLSearchParams(signRequest.queryParam);
      url += '?' + query.toString();
    }
    return {
      url,
      host: signRequest.host,
      method: signRequest.httpMethod.toUpperCase(),
      headers: signRequest.headers,
      body: signRequest.body
    };
  } catch (error) {
    console.error('Failed to get authorization');
    console.error(error);
    throw error;
  }
}
function percentCode(str: string): string {
  return encodeURIComponent(str)
    .replace(/\+/g, '%20')
    .replace(/\*/g, '%2A')
    .replace(/~/g, '%7E');
}
function hmac256(key: string, data: string): string {
  const hmac = crypto.createHmac('sha256', key);
  hmac.update(data, 'utf8');
  return hmac.digest('hex').toLowerCase();
}
function sha256Hex(bytes: any): string {
  const hash = crypto.createHash('sha256');
  const digest = hash.update(bytes).digest('hex');
  return digest.toLowerCase();
}
function processObject(map: Record<string, any>, key: string, value: any): void {
  // 如果值为空,则无需进一步处理
  if (value === null) {
    return;
  }
  if (key === null) {
    key = "";
  }
  // 当值为Array类型时,遍历Array中的每个元素,并递归处理
  if (Array.isArray(value)) {
    value.forEach((item, index) => {
      processObject(map, `${key}.${index + 1}`, item);
    });
  } else if (typeof value === 'object' && value !== null) {
    // 当值为Object类型时,遍历Object中的每个键值对,并递归处理
    Object.entries(value).forEach(([subKey, subValue]) => {
      processObject(map, `${key}.${subKey}`, subValue);
    });
  } else {
    // 对于以"."开头的键,移除开头的"."以保持键的连续性
    if (key.startsWith('.')) {
      key = key.slice(1);
    }
    map[key] = String(value);
  }
}
export function formDataToString(formData: Record<string, any>): string {
  const tmp: Record<string, any> = {};
  processObject(tmp, "", formData);
  let queryString = '';
  for (let [key, value] of Object.entries(tmp)) {
    if (queryString !== '') {
      queryString += '&';
    }
    queryString += encodeURIComponent(key) + '=' + encodeURIComponent(value);
  }
  return queryString;
}
// 固定变量签名计算方法
export interface FixedSignatureResult {
  httpMethod: string;
  canonicalUri: string;
  host: string;
  xAcsAction: string;
  xAcsVersion: string;
  signature: string;
  date: string;
  nonce: string;
  workspaceId: string;
  authorization: string;
}
export function calculateSignature(req: BatchTranslateRequest): SignedRequest {
  // 创建请求实例
  const signRequest = new Request(httpMethod, canonicalUri, host, xAcsAction, xAcsVersion);
  // 设置查询参数
  signRequest.queryParam = {
    RegionId: 'cn-beijing',
  };
  // 创建 body 的 Uint8Array
  const bodyUint8Array = encoder.encode(JSON.stringify({
    ...req,
    workspaceId,
  }));
  // 用于签名计算的 body
  signRequest.body = bodyUint8Array;
  signRequest.headers['content-type'] = 'application/json';
  // 获取签名
  const result = getAuthorization(signRequest);
  // 将 body 转换为 Base64 字符串用于传输
  const bodyBase64 = Buffer.from(bodyUint8Array).toString('base64');
  return {
    ...result,
    body: bodyBase64 // 返回 Base64 字符串而不是 Uint8Array
  };
}

Best practices for production

  • RequiredgetToken: complete authentication signing on your backend before sending translation requests.
  • Choose one import method: the full index.js bundle is sufficient. With on-demand imports, page translation requires page.js, and side-by-side translation requires paragraph.js.
  • Clean up before re-translating: before switching parameters or languages multiple times, call removeTranslations() first to prevent stale state from interfering with the new configuration.
  • Keep target and exclude selectors narrow: scope targetSelectors to your business containers, and use excludeSelectors to exclude navigation, code blocks, editing areas, and similar regions.
  • Avoid translating sensitive areas, such as input fields, editors, business script nodes, and template containers.
  • Avoid heavy logic in hooks: onTranslatingStart/End fire frequently. Avoid expensive operations that block the main thread.
  • Recommended for dynamic content: enable dynamic to support lazily rendered and streaming pages.

FAQ

Translation has no effect

  • Check that the scripts are loaded correctly (the full index.js, or core.js plus the required plugin).
  • Check that targetSelectors match elements on the page.
  • Check that excludeSelectors do not accidentally exclude the target area.
  • Check that the signing API returns a valid request structure.

rules / hooks do not take effect

  • Make sure the parameters are passed at the same level as pageTranslate / paragraphTranslate.
  • Call removeTranslations() before translating again.
  • Check that selector matches the paragraph commonAncestor or one of its ancestors.

The loading indicator is not visible

  • When translation is fast, the indicator disappears instantly. Set a minimum visible duration (for example, 300-500 ms) on your side.
  • Use data-source-hash as a unique identifier to prevent concurrent paragraphs from overwriting each other.

Where do I get the AK/SK?

  • Obtain them from the AccessKey module of the Alibaba Cloud platform.

Where do I get the workspaceId for the token service?

  • Log in to the Alibaba Cloud account that the AK/SK belongs to, and find the workspace details in the lower-left corner of the Model Studio console.
  • The workspace ID in the pop-up window is the required workspaceId. Click the copy icon to the right of the field to copy it directly.

API permission error

  • Tongyi Multimodal Translation is not activated: use the Alibaba Cloud primary account that owns the AK to activate the service in Model Studio.

Change log

March 2026

Version

Release date

Description

3.0.1

August 6, 2026

Support for translating page element attribute content (configuration parameter)

3.0.0

July 16, 2026

Major version upgrade: added on-demand imports, glossary/corpus/domain configuration, style overrides, and more configuration parameters

2.0.6

March 5, 2026

Added the lazyload and lazyOffset parameters for side-by-side translation