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
Integrate the JSSDK
Current version
Item | Value |
|---|---|
Version |
|
CDN root path |
|
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:
Method 1: Full bundle (recommended for getting started)
Include index.js once (it contains the core and all plugins) to use both page translation and side-by-side translation:
File | Description | URL |
|---|---|---|
| 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 SDK | https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/core.js |
| Page translation plugin | https://g.alicdn.com/code/npm/@alife/translate-js-sdk/3.0.1/page.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.jsfirst, then the plugins. - The global object is
window.AliTranslate, with the aliaswindow.__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 |
|---|---|---|---|
|
| Yes | Authentication signing function that returns a signed request ready to call the translation service |
|
| No | Glossary that improves the consistency of domain terms |
|
| No | Translation memory |
|
| No | Business domain (passed through to the translation request) |
|
| No | Chunk size threshold (affects request batching and throughput) |
|
| No | Maximum number of retries after a translation failure |
|
| No | Callback invoked when translation is complete |
PageTranslateConfig parameters
Parameter | Type | Required | Description |
|---|---|---|---|
|
| Yes | Target language |
|
| No | Source language. If not specified, the language is automatically detected. |
|
| No | Translation root node. The default value is |
|
| No | Excluded nodes (once matched, the entire subtree is not translated) |
|
| No | Element attributes that support translation |
|
| No | Whether to enable lazy-load translation |
|
| No | Viewport offset for lazy loading (px) |
|
| No | Lazy translation selectors (reserved field in the current version; prefer |
|
| No | Whether to watch for DOM changes and translate automatically |
|
| No | Initialization wait / dynamic translation throttle delay (ms) |
|
| No | Page translation rules (applied to the source text container) |
|
| No | Callback invoked before the translation is inserted |
|
| No | Callback invoked when translation of a node starts |
|
| No | Callback invoked when translation of a node ends |
ParagraphTranslateConfig parameters
Parameter | Type | Required | Description |
|---|---|---|---|
|
| Yes | Target language |
|
| No | Source language. If not specified, the language is automatically detected. |
|
| No | Translation root node. The default value is |
|
| No | Excluded nodes (once matched, not included in paragraph extraction) |
|
| No | Element attributes that support translation |
|
| No | Whether to enable lazy-load translation |
|
| No | Viewport offset for lazy loading (px) |
|
| No | Lazy translation selectors (reserved field in the current version; prefer |
|
| No | Whether to watch for DOM changes and translate automatically |
|
| No | Initialization wait / dynamic translation throttle delay (ms) |
|
| No | Forces translations to be inserted as blocks (on their own line) |
|
| No | Forces translations to be inserted inline (on the same line) |
|
| No | Style rules for side-by-side translation |
|
| No | Callback invoked before |
|
| No | Callback invoked when translation of a paragraph starts |
|
| 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.
// 通过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
};
}
// 通过calculateSignature方法生成签名
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.io.UnsupportedEncodingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
/**
* 签名请求接口
*/
interface SignatureRequest {
String getHttpMethod();
String getCanonicalUri();
String getHost();
String getXAcsAction();
String getXAcsVersion();
Map<String, String> getHeaders();
byte[] getBody();
Map<String, Object> getQueryParam();
void setHeaders(Map<String, String> headers);
void setBody(byte[] body);
void setQueryParam(Map<String, Object> queryParam);
}
/**
* 批量翻译请求数据类
*/
class BatchTranslateRequest {
private String scene;
private String sourceLanguage;
private boolean streaming;
private String targetLanguage;
private Map<String, String> text;
// 构造函数
public BatchTranslateRequest() {}
public BatchTranslateRequest(String scene,
String sourceLanguage, boolean streaming,
String targetLanguage, Map<String, String> text) {
this.scene = scene;
this.sourceLanguage = sourceLanguage;
this.streaming = streaming;
this.targetLanguage = targetLanguage;
this.text = text;
}
// Getters and Setters
public String getScene() { return scene; }
public void setScene(String scene) { this.scene = scene; }
public String getSourceLanguage() { return sourceLanguage; }
public void setSourceLanguage(String sourceLanguage) { this.sourceLanguage = sourceLanguage; }
public boolean isStreaming() { return streaming; }
public void setStreaming(boolean streaming) { this.streaming = streaming; }
public String getTargetLanguage() { return targetLanguage; }
public void setTargetLanguage(String targetLanguage) { this.targetLanguage = targetLanguage; }
public Map<String, String> getText() { return text; }
public void setText(Map<String, String> text) { this.text = text; }
}
/**
* 请求实现类
*/
class Request implements SignatureRequest {
private String httpMethod;
private String canonicalUri;
private String host;
private String xAcsAction;
private String xAcsVersion;
private Map<String, String> headers;
private byte[] body;
private Map<String, Object> queryParam;
public Request(String httpMethod, String canonicalUri, String host,
String xAcsAction, String xAcsVersion) {
this.httpMethod = httpMethod;
this.canonicalUri = canonicalUri != null ? canonicalUri : "/";
this.host = host;
this.xAcsAction = xAcsAction;
this.xAcsVersion = xAcsVersion;
this.headers = new HashMap<>();
this.body = null;
this.queryParam = new HashMap<>();
initHeader();
}
private void initHeader() {
Instant now = Instant.now();
String date = DateTimeFormatter.ISO_INSTANT.format(now);
String nonce = generateRandomHex(16);
this.headers.put("host", this.host);
this.headers.put("x-acs-action", this.xAcsAction);
this.headers.put("x-acs-version", this.xAcsVersion);
this.headers.put("x-acs-date", date);
this.headers.put("x-acs-signature-nonce", nonce);
}
private String generateRandomHex(int length) {
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[length];
random.nextBytes(bytes);
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
// Getters
@Override
public String getHttpMethod() { return httpMethod; }
@Override
public String getCanonicalUri() { return canonicalUri; }
@Override
public String getHost() { return host; }
@Override
public String getXAcsAction() { return xAcsAction; }
@Override
public String getXAcsVersion() { return xAcsVersion; }
@Override
public Map<String, String> getHeaders() { return headers; }
@Override
public byte[] getBody() { return body; }
@Override
public Map<String, Object> getQueryParam() { return queryParam; }
// Setters
@Override
public void setHeaders(Map<String, String> headers) { this.headers = headers; }
@Override
public void setBody(byte[] body) { this.body = body; }
@Override
public void setQueryParam(Map<String, Object> queryParam) { this.queryParam = queryParam; }
}
/**
* 签名后的请求结果
*/
class SignedRequest {
private String url;
private String method;
private String host;
private Map<String, String> headers;
private String body; // Base64 字符串
public SignedRequest(String url, String method, String host,
Map<String, String> headers, String body) {
this.url = url;
this.method = method;
this.host = host;
this.headers = headers;
this.body = body;
}
// Getters
public String getUrl() { return url; }
public String getMethod() { return method; }
public String getHost() { return host; }
public Map<String, String> getHeaders() { return headers; }
public String getBody() { return body; }
}
/**
* 固定签名结果接口
*/
interface FixedSignatureResult {
String getHttpMethod();
String getCanonicalUri();
String getHost();
String getXAcsAction();
String getXAcsVersion();
String getSignature();
String getDate();
String getNonce();
String getWorkspaceId();
String getAuthorization();
}
/**
* Node签名计算主类
*/
public class NodeSignature {
private static final String ALGORITHM = "ACS3-HMAC-SHA256";
private static final String ACCESS_KEY_ID = System.getenv("ACCESS_KEY_ID"); // 这里填入阿里云的AK
private static final String ACCESS_KEY_SECRET = System.getenv("ACCESS_KEY_SECRET"); // 这里填入阿里云的SK
private static final String WORKSPACE_ID = System.getenv("WORKSPACE_ID"); // 这里填入百炼的WorkspaceId
private static final String HTTP_METHOD = "POST";
private static final String CANONICAL_URI = "/anytrans/translate/batchForHtml";
private static final String X_ACS_ACTION = "BatchTranslateForHtml";
private static final String X_ACS_VERSION = "2025-07-07";
private static final String HOST = "anytrans.cn-beijing.aliyuncs.com";
private static final ObjectMapper objectMapper = new ObjectMapper();
/**
* 获取授权信息
*/
public static SignedRequest getAuthorization(SignatureRequest signRequest) {
try {
Map<String, Object> newQueryParam = new HashMap<>();
processObject(newQueryParam, "", signRequest.getQueryParam());
signRequest.setQueryParam(newQueryParam);
// 步骤 1:拼接规范请求串
String canonicalQueryString = signRequest.getQueryParam().entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(entry -> percentCode(entry.getKey()) + "=" + percentCode(String.valueOf(entry.getValue())))
.collect(Collectors.joining("&"));
// 请求体,当请求正文为空时,比如GET请求,RequestPayload固定为空字符串
byte[] requestPayload = signRequest.getBody() != null ? signRequest.getBody() : new byte[0];
String hashedRequestPayload = sha256Hex(requestPayload);
signRequest.getHeaders().put("x-acs-content-sha256", hashedRequestPayload);
// 将所有key都转换为小写
Map<String, String> lowerCaseHeaders = signRequest.getHeaders().entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().toLowerCase(),
Map.Entry::getValue
));
signRequest.setHeaders(lowerCaseHeaders);
List<String> sortedKeys = lowerCaseHeaders.keySet().stream()
.filter(key -> key.startsWith("x-acs-") || key.equals("host") || key.equals("content-type"))
.sorted()
.collect(Collectors.toList());
// 已签名消息头列表,多个请求头名称(小写)按首字母升序排列并以英文分号(;)分隔
String signedHeaders = String.join(";", sortedKeys);
// 构造请求头,多个规范化消息头,按照消息头名称(小写)的字符代码顺序以升序排列后拼接在一起
String canonicalHeaders = sortedKeys.stream()
.map(key -> key + ":" + lowerCaseHeaders.get(key))
.collect(Collectors.joining("\n")) + "\n";
String canonicalRequest = String.join("\n", Arrays.asList(
signRequest.getHttpMethod(),
signRequest.getCanonicalUri(),
canonicalQueryString,
canonicalHeaders,
signedHeaders,
hashedRequestPayload
));
System.out.println("canonicalRequest=========>\n" + canonicalRequest);
// 步骤 2:拼接待签名字符串
String hashedCanonicalRequest = sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
String stringToSign = ALGORITHM + "\n" + hashedCanonicalRequest;
System.out.println("stringToSign=========>" + stringToSign);
// 步骤 3:计算签名
String signature = hmac256(ACCESS_KEY_SECRET, stringToSign);
System.out.println("signature=YOUR_SIGNATURE>" + signature);
// 步骤 4:拼接 Authorization
String authorization = String.format("%s Credential=%s,SignedHeaders=%s,Signature=YOUR_SIGNATURE",
ALGORITHM, ACCESS_KEY_ID, signedHeaders, signature);
System.out.println("authorization=========>" + authorization);
lowerCaseHeaders.put("authorization", authorization);
// 构建完整的URL
String url = "https://" + signRequest.getHost() + signRequest.getCanonicalUri();
if (signRequest.getQueryParam() != null && !signRequest.getQueryParam().isEmpty()) {
String query = signRequest.getQueryParam().entrySet().stream()
.map(entry -> {
try {
return URLEncoder.encode(entry.getKey(), "UTF-8") + "=" +
URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.joining("&"));
url += "?" + query;
}
String bodyString = signRequest.getBody() != null ?
Base64.getEncoder().encodeToString(signRequest.getBody()) : null;
return new SignedRequest(url, signRequest.getHttpMethod().toUpperCase(),
signRequest.getHost(), lowerCaseHeaders, bodyString);
} catch (Exception error) {
System.err.println("Failed to get authorization");
error.printStackTrace();
throw new RuntimeException(error);
}
}
/**
* URL编码
*/
private static String percentCode(String str) {
try {
return URLEncoder.encode(str, "UTF-8")
.replace("+", "%20")
.replace("*", "%2A")
.replace("~", "%7E");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* HMAC-SHA256加密
*/
private static String hmac256(String key, String data) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hmacBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return bytesToHex(hmacBytes).toLowerCase();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* SHA256哈希
*/
private static String sha256Hex(byte[] bytes) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(bytes);
return bytesToHex(hashBytes).toLowerCase();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 字节数组转十六进制字符串
*/
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
/**
* 处理对象,将嵌套对象展平
*/
private static void processObject(Map<String, Object> map, String key, Object value) {
// 如果值为空,则无需进一步处理
if (value == null) {
return;
}
if (key == null) {
key = "";
}
// 当值为Array类型时,遍历Array中的每个元素,并递归处理
if (value instanceof List) {
List<?> list = (List<?>) value;
for (int i = 0; i < list.size(); i++) {
processObject(map, key + "." + (i + 1), list.get(i));
}
} else if (value instanceof Object[] || value.getClass().isArray()) {
Object[] array = (Object[]) value;
for (int i = 0; i < array.length; i++) {
processObject(map, key + "." + (i + 1), array[i]);
}
} else if (value instanceof Map) {
// 当值为Object类型时,遍历Object中的每个键值对,并递归处理
Map<?, ?> objectMap = (Map<?, ?>) value;
for (Map.Entry<?, ?> entry : objectMap.entrySet()) {
processObject(map, key + "." + entry.getKey(), entry.getValue());
}
} else {
// 对于以"."开头的键,移除开头的"."以保持键的连续性
if (key.startsWith(".")) {
key = key.substring(1);
}
map.put(key, String.valueOf(value));
}
}
/**
* 表单数据转字符串
*/
public static String formDataToString(Map<String, Object> formData) {
Map<String, Object> tmp = new HashMap<>();
processObject(tmp, "", formData);
return tmp.entrySet().stream()
.map(entry -> {
try {
return URLEncoder.encode(entry.getKey(), "UTF-8") + "=" +
URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.joining("&"));
}
/**
* 固定变量签名计算方法
*/
public static SignedRequest calculateSignature(BatchTranslateRequest req) {
try {
// 创建请求实例
Request signRequest = new Request(HTTP_METHOD, CANONICAL_URI, HOST, X_ACS_ACTION, X_ACS_VERSION);
// 设置查询参数
Map<String, Object> queryParam = new HashMap<>();
queryParam.put("RegionId", "cn-beijing");
signRequest.setQueryParam(queryParam);
// 创建请求体数据
Map<String, Object> bodyData = new HashMap<>();
bodyData.put("scene", req.getScene());
bodyData.put("sourceLanguage", req.getSourceLanguage());
bodyData.put("streaming", req.isStreaming());
bodyData.put("targetLanguage", req.getTargetLanguage());
bodyData.put("text", req.getText());
bodyData.put("workspaceId", WORKSPACE_ID);
// 创建 body 的字节数组
String jsonString = objectMapper.writeValueAsString(bodyData);
byte[] bodyBytes = jsonString.getBytes(StandardCharsets.UTF_8);
// 用于签名计算的 body
signRequest.setBody(bodyBytes);
signRequest.getHeaders().put("content-type", "application/json");
// 获取签名
SignedRequest result = getAuthorization(signRequest);
return result;
} catch (JsonProcessingException e) {
throw new RuntimeException("JSON序列化失败", e);
}
}
}
Best practices for production
- Required
getToken: complete authentication signing on your backend before sending translation requests. - Choose one import method: the full
index.jsbundle is sufficient. With on-demand imports, page translation requirespage.js, and side-by-side translation requiresparagraph.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
targetSelectorsto your business containers, and useexcludeSelectorsto 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/Endfire frequently. Avoid expensive operations that block the main thread. - Recommended for dynamic content: enable
dynamicto support lazily rendered and streaming pages.
FAQ
Translation has no effect
- Check that the scripts are loaded correctly (the full
index.js, orcore.jsplus the required plugin). - Check that
targetSelectorsmatch elements on the page. - Check that
excludeSelectorsdo 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
selectormatches the paragraphcommonAncestoror 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-hashas 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 |