foreword
Let’s talk about the application scenario. Recently, Android needs to load some third-party websites for users’ open use. These third-party websites are basically foreign websites in English, so the product demand hopes that the website can be translated into Chinese, similar to Google Translate in PC browsers. Web page
Steps for usage
1. Injection script
The code is as follows (example):
private void translateWeb() {
String javaScript = "javascript:function appendScrip() {" +
"var head= document.getElementsByTagName('head')[0]; var script= document.createElement('script'); script.src= 'https://res.zvo.cn/translate/translate.js'; head.appendChild(script);" +
"}" +
"appendScrip();";
bwvContent.evaluateJavascript(javaScript, new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
MyLogUtils.e("javaScript.onReceiveValue:" + s);
bwvContent.postDelayed(new Runnable() {
@Override
public void run() {
if (bwvContent==null) {
return;
}
String javaScript2 = "javascript:function startTranslate() {" +
"translate.localLanguage='zh-CN';translate.selectLanguageTag.show = false;translate.executeByLocalLanguage();" +
"}" +
"startTranslate();";
bwvContent.evaluateJavascript(javaScript2, new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
MyLogUtils.e("javaScript2.onReceiveValue:" + s);
}
});
}
}, 500);
}
});
}
important point
1. The bwvContent here uses Tencent's webview, and the evaluateJavascript method is used when executing the injected script. If the native webview does not have it, loadurl can also be used.
2. A 500ms delay operation is added to the first script injection and the second script injection, because in the actual measurement process, it is easy to fail to translate smoothly in the case of continuous execution, so a 500ms is added to increase the success rate. self debugging test
3. The injection of this method, the selection timing is placed in the onProgressChanged callback. When the loading progress progress==100, execute this method after a delay of 1000ms for automatic webpage translation, or call it when the user manually clicks the translation button. The timing The choice of self-debugging
Related links of the injected scripts used: web page multilingual translation js v1.2, updated translation interface- OSCHINA - Chinese Open Source Technology Exchange Community
Summarize
The overall effect is relatively smooth, and it is relatively simple to use. Here I am translating into Chinese. You can change zh-CN to en and other languages as needed, and even expand the switching buttons by yourself.