Skip to content
HangoverHangover
首页
项目收藏
留言板
github icon
  • 文章

      • 油猴 API
        • 免费翻译API
          • 百度翻译API

        百度翻译API

        author iconHangovercalendar icon2022年4月24日category icon
        • 油猴脚本
        tag icon
        • 油猴
        • 脚本猫
        • 翻译
        timer icon小于 1 分钟

        百度翻译API DEMO

        将剪切板内容翻译后再放入剪切板(需替换appid与key为自己的)

        // ==UserScript==
        // @name         百度翻译API
        // @namespace    https://bbs.tampermonkey.net.cn/
        // @version      0.1.0
        // @description  try to take over the world!
        // @author       You
        // @match        *://*/*
        // @grant        unsafeWindow
        // @grant        GM_xmlhttpRequest
        // @require      https://cdn.jsdelivr.net/npm/ddkr-zhangsan@1.0.0/md5.js
        // ==/UserScript==
        
        document.addEventListener("copy", () => { //监听复制
            navigator.clipboard.readText() //获取剪切板内容
                .then(value => {
                    let appid = 'YOU_APPID',  //百度翻译 APP ID
                        key = 'YOU_KEY', //密钥
                        salt = (new Date).getTime(),  //随机数
                        from = 'auto', //翻译源语言(自动)
                        sign = MD5(appid + value + salt + key), //md5签名
                        to; //翻译目标语言
                    new RegExp("[\u4E00-\u9FA5]+").test(value) ? to = 'en' : to = 'zh'; //判断是否是中文(中英互译)
                    GM_xmlhttpRequest({
                        method: "POST",
                        responseType: "json",
                        headers: {
                            "Content-type": "application/x-www-form-urlencoded"
                        },
                        data: `q=${encodeURI(value)}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${sign}`,
                        url: "https://fanyi-api.baidu.com/api/trans/vip/translate?",
                        onload: function (xhr) {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                navigator.clipboard.writeText(xhr.response.trans_result[0].dst); //将翻译后文本复制到剪切板
                            } else {
                                alert("服务器无响应或请求出错")
                            }
                        }
                    })
                })
                .catch(err => {
                    console.log(err)
                })
        })
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        上一页
        免费翻译API
        鸟无声兮山寂寂,夜正长兮风淅淅。 ──李华《吊古战场文》
        Copyright © 2023 Hangover