吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3150|回复: 23
收起左侧

[其他转载] 【JS】网页翻译

  [复制链接]
梦汐 发表于 2022-12-31 10:17
提取网页中所有文本节点,可根据需求来进行翻译或替换
)1~U0{QTWJHHM(B}DT`5~IJ.png
[JavaScript] 纯文本查看 复制代码
function listen(callback) {
    // 获取 HTML 文档中的所有元素,但不包括 下列 选择器的元素
    var exclude = ['head', 'pre', 'script', 'textarea']//排除名单
    var selectors = []
    exclude.forEach((item, index) => {
        selectors.push(item)//排除该元素
        selectors.push(item + ' *')//排除该元素后代
    })
    get(document.querySelectorAll('*:not(' + selectors.join(',') + ')'))//*:not(pre,pre *)
    // 创建 MutationObserver 对象
    let observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            // 遍历新添加的节点
            for (let i = 0; i < mutation.addedNodes.length; i++) {
                let node = mutation.addedNodes[i];
                // 如果节点是元素节点,就调用 get 函数
                if (node.nodeType === 1) {
                    callMyFunction(node)
                    function callMyFunction(param1) {
                        setTimeout(function () {
                            get([...param1.querySelectorAll('*'), param1])
                        }, 300);
                    }
                }
            }
        });
    });
    // 设置 MutationObserver 的参数,表示监听所有元素的变化
    let config = {
        childList: true,
        subtree: true
    };

    // 启动 MutationObserver
    observer.observe(document, config);

    function get(elements) {
        // 遍历所有元素
        for (let i = 0; i < elements.length; i++) {
            let element = elements[i];
            // 遍历元素的 childNodes
            for (let j = 0; j < element.childNodes.length; j++) {
                let node = element.childNodes[j];
                // 如果当前节点是一个文本节点(nodeType 为 3)且不包含子节点(nodeName 为 '#text'),就将文本添加到数组中
                if (node.nodeType === 3 && node.nodeName.toLowerCase() === '#text') {
                    // 过滤掉文本中的换行符

                    let text = node.nodeValue
                    var v = { a: false, b: false }
                    text.slice(0, 1) == " " ? v.a = true : v.a = false
                    text.slice(-1) == " " ? v.b = true : v.b = false
                    text = text.replace(/[\n\t\r]/g, '').trim();
                    // 如果文本不仅包含空白字符,就将它添加到数组中
                    if (/\S/.test(text)) {
                        //不处理只有数字和符号的文本
                        if (!/^[0-9\+\-\*\/\=><&\!@#\$%\^\*\\(\)\[\]\{\}_,.;',。、;’、]{1,}$/.test(text)) {
                            //---------------处理
                            //翻译text
                            //text = "$" + text
                            //---------------处理结束--显示
                            v.a == true ? text = " " + text : text
                            v.b == true ? text = text + " " : text
                            if (!element.matches('script,textarea')) {//单元素阻断,白名单
                                node.nodeValue = text
                                callback.call({ text: text, node: node, element: element })
                            } else {
                                //console.log("位于排除标签列表", element);
                            }
                        } else {
                            //console.log("只有数字和符号的文本", text);
                        }
                    }
                }
            }
        }
    }
}
let time = null;
var data = []
listen(
    function () {
        if (time !== null) {
            clearTimeout(time);
        }
        time = setTimeout(async () => {
            console.log(data);//抖动结束,开始翻译
            var sl = []
            data.forEach((item, index) => {//取text
                sl.push(item['text'])
            });
            //var tl = await translation_arr(sl)//返回一个数组[[翻译结果,源语言类型],...*]//使用的谷歌批量翻译API,这里就不提供了
            var tl = []
            sl.forEach((item, index) => {
                tl.push('[ 编辑:' + item + ',' + index + '] ')
            });

            tl.forEach((item, index) => {
                data[index]['node'].origText = data[index]['node'].nodeValue
                data[index]['node'].nodeValue = item//更改文本
            });
            //这里的this指向的是input
        }, 500)
        data.push(this)
    }
)
/* 监听文本节点被点击
document.onselectstart = function (e) {
    console.log(e.target,e.target.origText);
}*/

免费评分

参与人数 7吾爱币 +12 热心值 +6 收起 理由
2901110 + 1 + 1 谢谢@Thanks!
wushaominkk + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
jamessteed + 1 + 1 谢谢@Thanks!
love008 + 1 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
lfm333 + 1 + 1 谢谢@Thanks!
诗和远方代言人 + 1 谢谢@Thanks!
dns2018 + 1 已经处理,感谢您对吾爱破解论坛的支持!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

yyEnglish123 发表于 2022-12-31 11:12
大神,厉害啊
我是一个外星人 发表于 2022-12-31 11:44
xglys 发表于 2022-12-31 12:22
聪本 发表于 2022-12-31 12:23
哈哈哈哈哈感觉可以编点离谱的东西
Spiderman 发表于 2022-12-31 12:38
学习一下
Spiderman 发表于 2022-12-31 12:39
学习一下,努力学习
luodeman 发表于 2022-12-31 13:54
真棒,感谢大佬分享
yang1111502 发表于 2022-12-31 14:20
感谢分享
vip1639253946 发表于 2022-12-31 14:22
楼主厉害了
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-5 01:52

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表