3273 2 0 0
/*
* @name: 网页翻译(少数民族)
* @Author: akaltun773 mickro
* @version: 2.1
* @description: 调用谷歌翻译接口翻译整个网站
* @include: *
* @createTime: 2021-12-20 09:11:58
* @updateTime : 2021-12-21 00:51:04
*/
(function () {
/* 判断是否该执行 */
/* 网址黑名单制,遇到这些域名不执行 */
const blackList = [' '];

const hostname = window.location.hostname;
const key = encodeURIComponent('谷花泰:谷歌原生网页翻译:执行判断');
const isBlack = blackList.some(keyword => {
if (hostname.match(keyword)) {
return true;
};
return false;
});

if (isBlack || window[key]) {
return;
};
window[key] = true;

/* 开始执行代码 */
const config = {
initName: 'googleTranslate',
initElm: 'google_translate_elm',
/*多语言页面支持*/
multilanguagePage: true,
/* 哪种需要转 */
pageLanguage: 'auto',
/* 能转成啥 */
includedLanguages: 'ug,en,uz,kk,zh-CN',
/* 隐藏工具bar */
autoDisplay: false
};

/* 注入谷歌翻译脚本 */
const script = document.createElement('script');
script.src = `//translate.google.cn/translate_a/element.js?&cb=${config.initName}`;
script.async = true;
document.head.appendChild(script);

/* 创建谷歌翻译右下角的语言选择框容器 */
const div = document.createElement('div');
div.id = config.initElm;
div.setAttribute('style', `
position: fixed;
bottom: 5vw;
right: 35vw;
z-index: 999999999;
`);
document.documentElement.appendChild(div);

/* 谷歌翻译实例化函数 */
window[config.initName] = () => {
new window.google.translate.TranslateElement({
layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
multilanguagePage: config.multilanguagePage,
pageLanguage: config.pageLanguage,
includedLanguages: config.includedLanguages,
autoDisplay: config.autoDisplay
}, config.initElm);
};

/* 翻译dom函数 */
function observe({ targetNode, config = {}, callback = () => { } }) {
if (!targetNode) {
return;
};
config = Object.assign({
attributes: true,
childList: true,
subtree: true
}, config);
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
};

/* 翻译右下角的语言选择框 */
const initElm = document.querySelector(`#${config.initElm}`);
observe({
targetNode: initElm,
config: {
attributes: false
},
callback(mutationList, observer) {
/* 遍历节点 */
mutationList.forEach(mutation => {
Array.from(mutation.addedNodes, node => {
/* 清除 google image */
const googleImages = document.querySelectorAll(`#goog-gt-tt img, #${config.initElm} img`);
Array.from(googleImages, img => {
img.parentNode.removeChild(img);
});

/* 添加关闭按钮 */
if (node.className === 'goog-te-menu-value') {
const btnContent = document.querySelector('.goog-te-gadget-simple > span > a');
const closeBtn = document.createElement('span');
closeBtn.innerText = 'CLOSE | ';
closeBtn.addEventListener('click', (e) => {
initElm.parentNode.removeChild(initElm);
e.stopPropagation();
}, true);
btnContent.parentNode.insertBefore(closeBtn, btnContent);
};

});
/* 结束翻译 */
observer.disconnect();
});
}
});
})();
最新回复 (2)
  • 0 引用
    大佬 帮帮忙 谢谢
    • 轻创社区 - 有源软件体验中心
      4
        登录 注册
返回