### HTML Page Translation Setup with translate.js Source: https://context7.com/xnx3/translate/llms.txt This HTML snippet demonstrates a full integration example of translate.js, showcasing various configuration options for automatic website translation. It includes settings for language selection, ignoring specific elements, custom terminology, and advanced features like URL parameter control and dynamic content monitoring. ```html My Website

Welcome to Our Website

This is a demo of automatic translation.

Powered by translate.js

``` -------------------------------- ### Quick Usage Initialization Source: https://github.com/xnx3/translate/blob/master/extend/layui-i18n-object-translate/index.html Initializes various translation functionalities for quick use. This includes starting UI tips, listeners, language settings, and enabling all translation features. It also sets up DOMContentLoaded event listeners to trigger translation execution at different intervals after the page loads. ```javascript quickUse:function(){translate.visual.webPageLoadTranslateBeforeHiddenText(),translate.progress.api.startUITip(),translate.listener.start(),translate.request.listener.start(),translate.language.setUrlParamControl(),translate.language.translateLocal=!0,translate.whole.enableAll(),document.addEventListener("DOMContentLoaded",function(){translate.execute(),setTimeout(function(){translate.execute()},500),setTimeout(function(){translate.execute()},2e3)})} ``` -------------------------------- ### Initialize and Execute Translation with translate.js Source: https://context7.com/xnx3/translate/llms.txt Initializes the translate.js library by setting the local language, choosing a translation service, enabling dynamic content monitoring, and executing the translation process. This is the primary setup for enabling translation on a webpage. ```html ``` -------------------------------- ### Manage UI Tip for Translation API (JavaScript) Source: https://github.com/xnx3/translate/blob/master/extend/layui-i18n-object-translate/index.html Handles the display and management of UI tips during the translation process. It includes functions to set the UI tip status, remove specific CSS classes from elements, and start the UI tip by adding necessary styles and event listeners. ```javascript api:{isTip:!0,setUITip:function(e){translate.progress.api.isTip=e},removeChildClass:function(e,t){var a=e.childNodes;if(null==a||void 0===a);else if(a.length>0)for(var n=0;n-1||(l[a].node.className=l[a].node.className+" translate_api_in_progress")}),translate.lifecycle.execute.translateNetworkAfter.push(function(e){for(var t=translate.element.nodeToElement(e.nodes),a=0;a-1&&(t[a].className=t[a].className.replace(/translatejs-text-element-hidden/g,"")),t[a].className.indexOf("translate_api_in_progress")>-1&&(t[a].className=t[a].className.replace(/translate_api_in_progress/g,"")))}))}} ``` -------------------------------- ### Get Translation Service Host Queue Source: https://github.com/xnx3/translate/blob/master/extend/layui-i18n-object-translate/index.html Retrieves the queue of translation service hosts, prioritizing those with faster response times. If the queue is empty or stale, it re-initializes it from storage or by performing speed checks. This ensures the service always attempts to use the most optimal host. ```javascript getHostQueue:function(){ if(0==translate.request.speedDetectionControl.hostQueue.length){ var e=translate.storage.get("speedDetectionControl_hostQueue"); if(null==e||void 0===e||""==e){ "string"==typeof translate.request.api.host&& (translate.request.api.host=[""+translate.request.api.host]), translate.request.speedDetectionControl.hostQueue=[]; for(var t=0;t6e4&& translate.request.speedDetectionControl.checkResponseSpeed() } return translate.request.speedDetectionControl.hostQueue } ``` -------------------------------- ### Configuration Import/Export Source: https://context7.com/xnx3/translate/llms.txt Export and import translate.js configurations. This is useful for sharing settings, injecting configurations into iframes, or managing complex setups. ```APIDOC ## translate.config.get() ## translate.config.set(config: object) ### Description Export and import the current translate.js configuration. This functionality is valuable for saving and loading settings, sharing configurations between different parts of an application (like iframes), or managing complex translation setups. ### Method - `translate.config.get()`: Exports the current configuration as a JavaScript object. - `translate.config.set(config: object)`: Imports and applies a new configuration object. ### Endpoint N/A (Client-side JavaScript functions) ### Parameters #### Request Body (for `set` method) - **config** (object) - Required - A JavaScript object representing the configuration to be set. This object can include properties like `language`, `service`, `listener`, etc. ### Request Example ```javascript // Export the current configuration var currentConfig = translate.config.get(); console.log(JSON.stringify(currentConfig)); // Import a new configuration (useful for iframe injection or setup) translate.config.set({ language: { local: 'chinese_simplified', defaultTo: 'english', select: { show: true, languages: 'english,chinese_simplified,japanese' } }, service: 'client.edge', listener: { use: true } }); translate.execute(); ``` ### Response (for `get` method) #### Success Response (200) - **config** (object) - The current configuration of the translate.js library. #### Response Example (for `get` method) ```json { "language": { "local": "english", "defaultTo": "chinese_simplified", "select": { "show": false } }, "service": "client.web", "listener": { "use": false } } ``` ``` -------------------------------- ### Configure Translation Service with translate.service.use() Source: https://context7.com/xnx3/translate/llms.txt Selects the translation service channel to be used by the library. The 'client.edge' option offers a free, client-side translation solution that requires no server setup or registration. ```javascript // Use the free client-side Edge translation service (no registration required) translate.service.use('client.edge'); // Use the default translate.service API translate.service.use('translate.service'); // For production environments, consider using enterprise-grade services // See documentation: http://translate.zvo.cn/545867.html ``` -------------------------------- ### Vue 3 Plugin Setup with TypeScript Source: https://context7.com/xnx3/translate/llms.txt This snippet demonstrates how to set up the translate.js plugin for a Vue 3 application using TypeScript. It configures translation services, language settings, and enables various monitoring and translation features. ```typescript // src/translate.ts import { translateJsVueUseModel, translate } from 'i18n-jsautotranslate/vue/vue3/translateVue3TS.ts'; translate.vue3.config = function(app) { // Set available languages window.translate.selectLanguageTag.languages = 'chinese_simplified,english,korean,japanese'; // Set local language window.translate.language.setLocal('chinese_simplified'); // Enable loading indicator window.translate.progress.api.startUITip(); // Use free client-side translation translate.service.use('client.edge'); // Enable AJAX monitoring translate.request.listener.start(); // Enable DOM change monitoring translate.listener.start(); // Enable whole-element translation for better semantics translate.whole.enableAll(); // Execute translation translate.execute(); }; export { translateJsVueUseModel, translate }; ``` ```typescript // src/main.ts import { createApp } from 'vue'; import App from './App.vue'; import { translateJsVueUseModel } from './translate'; const app = createApp(App); app.use(translateJsVueUseModel); app.mount('#app'); ``` ```vue ``` -------------------------------- ### Fault Tolerance for Text Node Creation Source: https://github.com/xnx3/translate/blob/master/extend/layui-i18n-object-translate/index.html Provides a fault tolerance mechanism for `document.createTextNode`. It intercepts text node creation, potentially replacing the text with a translated version if available in the history, and stores the original and translated text. It also manages enabling and disabling this functionality based on language change and execution start events. ```javascript faultTolerance:{documentCreateTextNode:{originalCreateTextNode:null,node:null,use:function(){null==translate.faultTolerance.documentCreateTextNode.node&&(translate.faultTolerance.documentCreateTextNode.node=new Map),translate.lifecycle.changeLanguage.push(function(e){translate.isTranslate(e)?translate.faultTolerance.documentCreateTextNode.enable():translate.faultTolerance.documentCreateTextNode.disable()}),translate.lifecycle.execute.start.push(function(e){0===translate.executeNumber&&translate.isTranslate(e.to)&&translate.faultTolerance.documentCreateTextNode.enable()})},enable:function(){null==translate.faultTolerance.documentCreateTextNode.originalCreateTextNode&&(translate.faultTolerance.documentCreateTextNode.originalCreateTextNode=document.createTextNode,document.createTextNode=function(e){var t=!1,a=null;if(translate.executeTriggerNumber>0&&"string"==typeof e&&e.length>0){var n=translate.history.translateText.originalMap.get(e);"string"==typeof n&&n.length>0&&(a=e,e=n,t=!0)}const r=translate.faultTolerance.documentCreateTextNode.originalCreateTextNode.call(this,e);return t&&(translate.faultTolerance.documentCreateTextNode.node.set(r,{originalText:a,resultText:e}),translate.node.set(r,{attribute:"",originalText:a,resultText:e,translateTexts:{},whole:!0,translateResults:{\[a\]:1},lastTranslateRenderTime:Date.now()})),r})},disable:function(){null!=translate.faultTolerance.documentCreateTextNode.originalCreateTextNode&&(document.createTextNode=translate.faultTolerance.documentCreateTextNode.originalCreateTextNode,translate.faultTolerance.documentCreateTextNode.originalCreateTextNode=null)}}} ``` -------------------------------- ### translate.language.getLocal() - Get Original Page Language Source: https://context7.com/xnx3/translate/llms.txt Get the original language of the webpage content. ```APIDOC ## translate.language.getLocal() - Get Original Page Language ### Description Get the original language of the webpage content. ### Method `getLocal()` ### Endpoint N/A (Client-side function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Get the page's original language var localLang = translate.language.getLocal(); console.log('Page original language: ' + localLang); // Check if translation is needed if (translate.language.getLocal() !== translate.language.getCurrent()) { console.log('Page is being translated'); } ``` ### Response #### Success Response (string) - **localLang** (string) - The language code of the original page content (e.g., 'english', 'chinese_simplified'). ``` -------------------------------- ### Initialize Translation Core Components Source: https://github.com/xnx3/translate/blob/master/extend/layui-i18n-object-translate/index.html Initializes the core components of the translation system if not already initialized. This includes setting up data structures for nodes, translation history, and language names. It also pushes a function to the `translate.lifecycle.execute.start` event to handle initial trigger execution and nomenclature data processing. ```javascript init:function(){void 0===translate.init_execute&&(translate.init_execute="已进行",null==translate.node.data&&(translate.node.data=new Map),null==translate.history.translateText.resultMap&&(translate.history.translateText.resultMap=new Map),null==translate.history.translateText.originalMap&&(translate.history.translateText.originalMap=new Map),null==translate.language.name&&translate.language.generateLanguageNameObject(),translate.lifecycle.execute.start.push(function(e,t){if(void 0===translate.init_first_trigger_execute){for(var a in translate.init_first_trigger_execute=1,translate.nomenclature.data)if(translate.nomenclature.data.hasOwnProperty(a))for(var n in translate.nomenclature.data[a])if(translate.nomenclature.data[a].hasOwnProperty(n))for(var r in translate.nomenclature.data[a] ``` -------------------------------- ### Get Original Page Language - JavaScript Source: https://context7.com/xnx3/translate/llms.txt Get the original language of the webpage content before any translation is applied. This function is helpful for determining if translation is necessary or for logging purposes. ```javascript // Get the page's original language var localLang = translate.language.getLocal(); console.log('Page original language: ' + localLang); // Check if translation is needed if (translate.language.getLocal() !== translate.language.getCurrent()) { console.log('Page is being translated'); } ``` -------------------------------- ### translate.language.getCurrent() - Get Current Display Language Source: https://context7.com/xnx3/translate/llms.txt Retrieve the language currently being displayed to the user. ```APIDOC ## translate.language.getCurrent() - Get Current Display Language ### Description Retrieve the language currently being displayed to the user. ### Method `getCurrent()` ### Endpoint N/A (Client-side function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Get current display language var currentLang = translate.language.getCurrent(); console.log('Currently displaying: ' + currentLang); // Output: "english" or "chinese_simplified" etc. // Use for conditional logic if (translate.language.getCurrent() === 'english') { // Load English-specific resources } ``` ### Response #### Success Response (string) - **currentLang** (string) - The language code of the currently displayed language (e.g., 'english', 'chinese_simplified'). ``` -------------------------------- ### Execute Render Finish Timing and Logging Source: https://github.com/xnx3/translate/blob/master/extend/layui-i18n-object-translate/index.html Tracks the execution time of the render finish process, calculates the total time, and logs detailed timing information including translated languages and texts. It relies on the translate.time.execute.data object to store timing metrics. ```javascript translate.lifecycle.execute.renderFinish.push(function(e,t){translate.time.execute.data[e].finishTime=(new Date).getTime(),translate.time.execute.data[e].allTime=translate.time.execute.data[e].finishTime-translate.time.execute.data[e].startTime;var a=new Array,n=new Array;translate.nodeQueue[e];for(var r in translate.nodeQueue[e].list)if(translate.nodeQueue[e].list.hasOwnProperty(r)&&("string"!=typeof r||r.length<1))for(var s in n.push(r),translate.nodeQueue[e].list[r])translate.nodeQueue[e].list[r].hasOwnProperty(s)&&a.push(translate.nodeQueue[e].list[r][s].original);translate.time.execute.data[e].translateLanguages=n,translate.time.execute.data[e].translateTexts=a,translate.log("[time][translate.execute()] "+translate.time.execute.data[e].allTime+"ms "+(void 0!==translate.time.execute.data[e].translateNetworkBeforeTime?"(search&cache "+(translate.time.execute.data[e].translateNetworkBeforeTime-translate.time.execute.data[e].startTime)+"ms)":"")+(a.length>0?" , ["+n+"] : ("+a.length+")["+a.slice(0,3)+(a.length>3?". ...":"")+"]":""))}) ``` -------------------------------- ### Core API - Set Translation Service Source: https://context7.com/xnx3/translate/llms.txt Configures which translation service channel to use. The 'client.edge' option provides free translation without server setup. ```APIDOC ## POST /translate/service/use ### Description Configures which translation service channel to use. The 'client.edge' option provides free translation without server setup. ### Method POST ### Endpoint /translate/service/use ### Parameters #### Query Parameters - **serviceName** (string) - Required - The name of the translation service to use (e.g., 'client.edge', 'translate.service'). #### Request Body - **None** ### Request Example ```javascript // Use the free client-side Edge translation service (no registration required) translate.service.use('client.edge'); // Use the default translate.service API translate.service.use('translate.service'); // For production environments, consider using enterprise-grade services // See documentation: http://translate.zvo.cn/545867.html ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of setting the translation service. #### Response Example ```json { "status": "Translation service set to client.edge" } ``` ``` -------------------------------- ### Enable Mouse Selection Translation with translate.selectionTranslate.start() Source: https://context7.com/xnx3/translate/llms.txt This feature enables instant translation of selected words or phrases on the page via mouse selection. Once enabled, users can highlight text to see its translation in a popup. ```javascript // Enable mouse selection translation translate.selectionTranslate.start(); // Now users can select any text on the page // and see its translation in a popup translate.execute(); ``` -------------------------------- ### Get Node Name (JavaScript) Source: https://github.com/xnx3/translate/blob/master/extend/layui-i18n-object-translate/index.html Retrieves the node name or tag name of an HTML element. Returns an empty string if the element or its name/tag is null or undefined. Logs a warning for unresolvable node names. ```javascript getNodeName:function(e){if(null==e||void 0===e)return"";if(null==e.nodeName||void 0===e.nodeName)return"";e.nodeName;return"string"==typeof e.nodeName?e.nodeName:"string"==typeof e.tagName&&e.tagName.length>0?e.tagName:(translate.log("warn : get node name is null, this node ignore translate. node : "),translate.log(e),"")} ``` -------------------------------- ### Initialize and Manage MutationObserver for Real-time Translation Source: https://github.com/xnx3/translate/blob/master/extend/layui-i18n-object-translate/index.html Sets up and manages a MutationObserver to detect changes in the DOM for real-time translation. It defines configuration for observing attribute changes, child list modifications, and character data changes. The callback function processes detected changes, filters out ignored nodes, and triggers translation execution for relevant nodes. ```javascript listener:{isStart:!1,use:!1,start:function(){void 0===translate.temp_listenerStartInterval&&(translate.listener.use=!0)},ignoreNode:[],translateExecuteNodeIgnoreExpireTime:1e3,addIgnore:function(e,t,a){let n="";n="string"==typeof e?e:nodeuuid.uuid(e),translate.listener.ignoreNode[n]={addtime:Date.now()+t,text:a}},refreshIgnoreNode:function(){var e=Date.now();for(const t in translate.listener.ignoreNode)translate.listener.ignoreNode[t].addtimeDate.now()&&(t=!1)),!0===t&&0===e.nodeValue.trim().length&&(t=!1),t},addListener:function(){if(1!=translate.listener.isStart){translate.listener.isStart=!0,translate.listener.config={attributes:!0,childList:!0,subtree:!0,characterData:!0,attributeOldValue:!0,characterDataOldValue:!0},translate.listener.callback=function(e,t){var a=[]for(let t of e){let e=[]if("childList"===t.type){if(t.addedNodes.length>0&&(e=t.addedNodes),t.removedNodes.length>0)for(var n=0;n-1&&r.condition(t.target)))continue}var s=t.target.getAttributeNode(t.attributeName);translate.listener.nodeValueChangeNeedTranslate(s)&&(translate.node.delete(s),e=[s])}else if("characterData"===t.type){translate.listener.nodeValueChangeNeedTranslate(t.target)&&(translate.node.delete(t.target),e=[t.target])}for(let t of e){for(var l=!1,i=0;i0){translate.time.log("监听到元素发生变化,"+a.length+"个元素");var o=[]for(let e of a){for(var u=!1,d=0;dDate.now()&&"string"==typeof e.nodeValue&&e.nodeValue==translate.listener.ignoreNode[t].text||o.push(e)}if(o.length<1)return;translate.time.log("将监听到的发生变化的元素进行整理,得到"+o.length+"个元素,对其进行翻译"),translate.execute(o)}},translate.listener.observer=new MutationObserver(translate.listener.callback);for(var e=translate.getDocuments(),t=0;t