3 Star 2 Fork 147

jason.fy / translate

forked from 鬼画符 / translate 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

translate.js

Two lines of js realize automatic html translation.
No need to change the page, no language configuration file, no API key, SEO friendly!

Current English DOC | 查阅中文文档

Characteristic

  • Easy to use. Without any preliminary preparation, you can directly add a few lines of code to have the ability to automatically switch multiple languages.
  • No additional workload. There is no need to modify the page itself, no language files that need to be configured separately for all languages, and no need for you to call the code of the text area to be displayed on the page itself. I think that is too unfriendly for technicians. Moreover, it doesn't need you to apply for any key to XXX website. It is open and ready to use.
  • Extremely flexible and scalable. You can specify whether it will only translate certain specified areas, display the drop-down box when switching languages, or place multiple language switching buttons, and specify that certain specific elements will not be translated and ignored
  • Automatically match languages. Automatically switch the language used in the user's country according to the user's country
  • Instant translation ability. Built-in cache preloading mechanism, as long as the translated page is viewed again, it will achieve instant translation effect, giving the user the impression that the page is originally in this language, not translated by a third party.
  • Free for permanent use. I am keen on open source. There are twenty or thirty open source projects. The original purpose of this project is to break the language boundary of web communication. The world is one! Of course, if your project is relatively large, and the daily visits reach millions or tens of millions, we still recommend that you deploy it privately.
  • Search engine friendly. It does not affect the inclusion of your own website search engine. The source code of the webpage crawled by the crawler will not be changed. You can rest assured.

Online experience

http://res.zvo.cn/translate/demo.html

Try using other people's websites first

效果

  1. Open a webpage at random
  2. Right click - review elements
  3. Paste the following code: var head= document.getElementsByTagName('head')[0]; var script= document.createElement('script'); script.type= 'text/javascript'; script.src= 'https://res.zvo.cn/translate/inspector_v2.js'; head.appendChild(script);
  4. Enter to execute
  5. At the top left corner of the current page, there is a big language switch. Try switching.

Quick use

At the end of the page, </html> before, Add the following code. Generally, the select switch tab for selecting language appears at the bottom of the page. In fact, it is so simple

<script src="https://res.zvo.cn/translate/translate.js"></script>
<script>
translate.setUseVersion2(); //Set to use v2.x version
translate.language.setLocal('chinese_simplified'); //Set the local language (the language of the current page). If not set, the language of the text displayed on the current page will be automatically recognized by default. Can be filled in, such as 'english'、'chinese_simplified' , please refer to the description below the document.
translate.execute(); // Translate
</script>

More extended usage

Specify the location of the select selection box for switching languages

Where you want to display on your page, just put the following one.

<div id="translate"></div>

Mainly this id="translate" The button for switching languages will be automatically assigned to this ID. Of course, you don't have to be div, you can

<span id="translate"></span>

CSS beautification switch language button

Css can be used to control the display position and beauty of switching language selection. For example:

<style>
.translateSelectLanguage{
	position: absolute;
	top:100px;
	right:100px;
}
</style>

This is the <select> tag that controls the switching language

Set whether the select switch language will appear automatically

/*
 * Whether to display the selection box of select language, and true to display; False does not display. Default is true
 * Note that this line should be placed in translate.execute(); above
 */
translate.selectLanguageTag.show = false;
translate.execute();

The usage scenario is, if you use:

<a href="javascript:translate.changeLanguage('en');">Switch to English</a>

If this switch mode is used, the selection from the select drop-down box will not be used, and you can use this mode to not display.
Of course, you can also use css to control its display. For example:

<style>
#translate{
	display:none;
}
</style>

Ignore the specified tag tag during translation

translate.ignore.tag.push('span'); //When translating, add the tag that you want to ignore and do not translate. Anything in this tag will not be translated.

When translating, add the tag that you want to ignore and do not translate. Anything in this tag will not be translated.
If you want to see which tag tags are currently ignored, you can directly execute console. log (translate. ignore. tag) View

Note that this line should be placed in translate.execute(); above

Ignore the specified class value during translation

translate.ignore.class.push('test');	//When translating, add the class tag that you want to ignore and do not translate. Anything in this tag will not be translated.

When translating, add the class tag that you want to ignore and do not translate. Anything in this tag will not be translated.
If you want to see which tag tags are currently ignored, you can directly execute console. log (translate. ignore. class) View Note that this line should be placed in translate.execute(); above

Translate the specified area

var documents = [];
documents.push(document.getElementById('test1'));
documents.push(document.getElementById('test2'));
documents.push(document.getElementById('test3'));
translate.setDocuments(documents); //Specifies the collection of elements to be translated. One or more elements can be passed in. If not set, the entire page will be translated by default

You can use translate.setDocuments(...) to specify the collection of elements to be translated, and you can pass in one or more elements. If this is not set, the entire page will be translated by default. Note that this line should be placed in translate.execute(); above

Js active language switching

For example, click a link to display the English interface

<a href="javascript:translate.changeLanguage('english');" class="ignore">Switch to English</a>

You can quickly switch to the specified language by passing in the target language of the translation. Specific languages can be consulted: http://api.translate.zvo.cn/doc/language.json.html
Where class="ignore" adds this class, which means that the a tag will not be translated

Automatically switch users' languages according to their country

When the user first opens the web page, the language of the current user's country will be automatically determined to switch to the language of the user's country.
If the user manually switches to another language, and then uses it again, the user's choice will prevail.

translate.setAutoDiscriminateLocalLanguage();	//Set the language of the user's country to switch automatically when the user uses it for the first time

Set the local language (the language of the current page)

translate.language.setLocal('chinese_simplified'); //Set the local language (the language of the current page). If not set, the language of the text displayed on the current page will be automatically recognized by default.

Specific languages can be consulted: http://api.translate.zvo.cn/doc/language.json.html
If not set, the default is Simplified Chinese : chinese_simplified
When selecting a language, if you use it for the first time, the local language set here is selected by default.

Note that this line should be placed in translate.execute(); above

Adapt the rendering display of data dynamically loaded by ajax

Under normal circumstances, there is a great possibility of such demand:

  1. In the page, you need to request the back-end server to obtain data through ajax, and then render and display the data.
  2. Pop-up prompt in the page (such as msg.js Medium msg.info('Hello'); )This prompt is loaded by js. The prompt text also needs to be translated, You can add the following line of code to meet the above requirements.
translate.listener.start();	//Enable the monitoring of html page changes, and automatically translate the changes. Note that the change area here refers to the area set using translate.setDocuments(...) . If it is not set, it is necessary to monitor the change of the whole page

It is recommended to put it before the line translate.execute()

matters needing attention

If you manually set translate.setDocuments(...) , you will not listen to the entire page, but only listen to changes in the area set by setDocuments(...) .

Privatization deployment translation service interface

In some government agencies and internal projects of large groups, when there are strong requirements for data privacy and security, and you want to provide highly reliable translation services for your own customers, you can privatize the translation service interface and do not go through our open translation interface, so as to achieve full control of security and back-end services.
For the actual deployment method, please refer to: https://github.com/xnx3/translate_service
After deployment, click translate.execute(); Before, add a line of code as follows:

translate.request.api.host='http://121.121.121.121/'; //Replace the IP address in this with the IP address of your server. Pay attention to the beginning and the end
translate.execute();

In this way, the translation request interface will go to your own server.

Examples of actual use scenarios

Click a language to switch in a common website

As shown in the figure below, there should be several language switches at a certain location in the website
Add the following code directly at the end of its html code:

<!-- Add a language switch button. Note that a class="ignore" added to ul means that this code will not be translated -->
<ul class="ignore">
	<li><a href="javascript:translate.changeLanguage('english');">English</a></li>|
	<li><a href="javascript:translate.changeLanguage('chinese_simplified');">简体中文</a></li>|
	<li><a href="javascript:translate.changeLanguage('chinese_traditional');">繁體中文</a></li>
</ul>

<!-- Js introducing multi-language switching -->
<script src="https://res.zvo.cn/translate/translate.js"></script>
<script>
	translate.setUseVersion2(); //Set to use v2. x version
	translate.selectLanguageTag.show = false; //The selection language of the non-existent select
	translate.execute();
</script>

Participate in

You can fork the project directly. Note that it is the github warehouse [https://github.com/xnx3/translate](https://github.com/xnx3/translate), non-gitee warehouse
If you have changed any code, please note your name and your personal home page in it, which is your participation and contribution. For example, Mr. Chen participated in the character judgment of Japanese translation, which can be as follows:

/*
	If it contains Japanese, return true: contains
	Participant: Chen https://www.chenmouren.com/xxxxx.html
*/
japanese:function(str){
	if(/.*[\u0800-\u4e00]+.*$/.test(str)){ 
		return true
	} else {
		return false;
	}
},

Version

Note that v1.x is slightly different from v2.x. You can use console. log (translate. version) View the version currently used. In addition, for the relevant description of v1.x version, see: instructions | online demo

v1.0

It will be released in February 2022, providing multilingual support, enabling the webpage to quickly switch languages without changing.

v2.0

It will be released in December 2022, adding more extension methods.

  1. Ignorable tag tags can be customized and will be ignored during translation
  2. Ignorable classes can be customized, which will be ignored during translation
  3. The default built-in class="ignore" is the ignored class. You can add this attribute to a tag to make it skip translation.
  4. Add a caching mechanism. The results will be cached after a translation. After the translation, the results will be translated in seconds and the experience will be greatly improved.
  5. Increase the ability of local translation, and support the customized translation area.
  6. Optimize the problem that the content of the placeholder in the input box is not translated
  7. Problems that cannot be tested when optimizing local use (file protocol). Now the local can also be used and tested normally.
  8. Fix the problem that countless layers of font labels will be added during translation
  9. When repairing translation, such as Chinese translation into Korean, the mouse will repeatedly translate the translated Korean after several times, resulting in inaccurate translation results.
  10. Open translation cloud service platform interface http://api.translate.zvo.cn/doc/index.html

v2.1

  1. The local language is assigned to use v2 version translation by default
  2. Add translate.language.connector() to adapt the connector of the sentence independently
  3. Add an area annotated by <!-- --> and do not translate it
  4. Add English README document
  5. Increase the translation of alt, meta keywords and descriptions of pictures
  6. Optimize and judge whether the local language is the same as the target language to be translated. If it is the same, then no translation is required
  7. Add translate.listener.start() It can automatically translate the changed areas of the current page, such as rendering after loading data with ajax
  8. translate.execute(...) Add a translation area that can be imported. The imported area is only used for one-time translation and will not affect the value of setDocuments(...)
  9. The task queue mechanism is added to completely solve the problem that there is a very small probability of text omission during translation.
  10. Add translate.setAutoDiscriminateLocalLanguage(); When users use it for the first time, they can automatically identify the language of their country for switching

v2.2

  1. Open the private one-click deployment of the back-end translation service interface and open source.
  2. Greatly optimize the accuracy of sentence translation to the extent of Baidu Translation and Google Translation
  3. Add a configurable id for an element, ignore it and do not translate it
  4. Add separate judgment for connector recognition to improve translation accuracy
  5. Add the ability to configure separately for translate.request.api.host for private deployment
  6. Add inspector_v2.js is used for the quick conversion experience of v2 version, and the quick experience in readme is to use this v2 version by default.
  7. Add translate.language.autoRecognitionLocalLanguage(); If the language of the current page is not set manually, the language will be recognized automatically
  8. Add translate.language.getLocal() The user obtains the language of the current page (if not set, the language will be automatically recognized according to the text currently displayed on the page)
  9. Add translate.selectLanguageTag.selectOnChange Used to provide override of select onchange event for better extension
  10. Some unexpected problems in translation when optimizing Chinese-English mixing
  11. optimization meta、keywords Replacement problems
  12. If there is', such as let's' in English when optimizing to English
  13. Optimize ignore's judgment on how many cases the class name is ignored
  14. Open the back-end translation service interface document for better expansion and use
  15. Fix the problem that tag sometimes fails, such as local translation in listening status

These open source projects are being used

The ability of automatic translation has been put into the following open source projects:
kefu.js H5 online customer service, introduce a line of js code to use immediately! Support mobile phones, computers, APP, and applets. One-click deployment of your own private SAAS cloud customer service platform
Pear Admin Layui Pearl Admin is an out-of-the-box front-end development template that extends the native UI style of Layui, integrates third-party open source components, provides a convenient and rapid development method, and continues LayuiAdmin
Layui Translation component ...

Outstanding open source projects and community recommendations

Featbit A 100% open-source feature flags management platform LinkWeChat LinkWeChat It is an open source SCRM system based on enterprise WeChat, and a comprehensive solution for enterprise private domain traffic management and marketing.
IoTSharp IoTSharp is an open source Internet of Things basic platform based on. Net Core, supporting HTTP, MQTT and CoAp protocols
Cloud of flow Information and digital service providers

Other instructions

The current version of v2.0 is still in the optimization stage and is not a perfect and stable version. Currently, only most websites have been tested for perfect adaptation, but there will be omissions. As the number of websites used increases, the bugs found will be gradually fixed. The stable version is expected to be released in the next three to four months. When you use the v2 version, you can directly use our js source. If you have localization requirements, you can place localization after the stable version is released later.
I love open source. If you are the author of an open source framework and want to add this multilingual switching capability to your open source project, but encounter difficulties when accessing it, welcome to join the QQ group below to explain which open source software author you are, and I will fully assist you. Friends who are willing to open source are worthy of respect and support.
This cloud server platform can be deployed privately. If you have any needs in this regard, you can also contact me. But this deployment takes several hours to half a day, and we also need to pay our colleagues. The epidemic has been relatively difficult for three years, so there is no way to help with the deployment free of charge. It will cost hundreds of labor costs to provide paid deployment. I hope you can understand.

communication

If you encounter any abnormal situation during use, please mention the issues and write down the problems you encounter in detail. If you can, please also write down your website, so that we can test more fully to quickly locate the problem
Author WeChat:xnx3com
Email: 921153866@qq.com
Communication QQ group:181781514
github: https://github.com/xnx3/translate
gitee: https://gitee.com/mail_osc/translate

VIP service

Currently, translate.js is based on js to translate the current html, and most scenarios are sufficient. However, if you view the page source code, you will find that the source code does not change and is in an untranslated state. If you want to translate the page source code directly, you can click here to view our extended version

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

两行js实现html全自动翻译,页面无需改动,无语言配置文件,无API Key,对SEO友好! 展开 收起
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/feiyit/translate.git
git@gitee.com:feiyit/translate.git
feiyit
translate
translate
master

搜索帮助