开发一款有翻译功能的Google浏览器插件(扩展程序)

找遍了Chrome 网上应用店,也没有找到我想要的翻译扩展程序(程序翻译结果不满意),于是打算自己写一个,感觉还可以~

扩展程序效果图:

整个扩展程序只有5个文件

icon.png是扩展程序的图标, 就是扩展程序效果图右上角的那个小图标。

index.html是扩展程序的主页面, 也可以直接打开在浏览器上运行的,不过会独占一个标签页,弄成浏览器扩展程序后就可以在任何标签页上运行,方便多了!

index.js是index.html需要引入的JavaScript文件。

jquery.js就是jQuery的源码, 主要用来发送ajax请求, 懒得用自己封装的了。

manifest.json就是实现把页面变成扩展程序的关键文件, 这是一个Chrome插件必不可少的文件,用来配置所有和插件相关的配置,必须放在根目录。

翻译功能用的是网易有道词典的接口, 网易有道词典的翻译结果还是很满意的。

HTML和JS文件内容比较简单, 我就直接贴代码了。

index.html文件内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>在线翻译</title>
    <script src="./jquery.js"></script>
    <style>
        #all{
            text-align: center;
        }
        .button-box{
            width: 250px;
            margin: 50px auto;
        }
        .button-box button{
            width: 200px;
            height: 40px;
            font-size: 18px;
        }
        #auto-pronunciation{
            margin-top: 5px;
            background-color: rgb(50, 226, 203);
        }
        #translate{
            background-color: #03A9F4;
        }
        #input, #output{
            width: 90%;
            font-size: 18px;
            margin-top: 10px;
        }
        @media screen and (max-width: 500px){
            #input, #output{
                padding: 10px;
                font-size: 16px;
            }
            #translate{
                left: calc(50% - 100px);
            }
        }
    </style>
</head>
<body>
    <div id="all">
        <textarea id="input" cols="30" rows="6" placeholder="请输入你要翻译的内容:" ></textarea>
        <textarea id="output" cols="30" rows="6"></textarea>


        <div class="button-box">
            <button id="translate">翻译</button>
            <button id="auto-pronunciation" >自动发音: 开</button>
        </div>
    </div>

    <script src="./index.js"></script>
</body>
</html>

index.js的文件内容:

        const translate = document.getElementById('translate');
        const auto_pronunciation = document.getElementById('auto-pronunciation');
        const input = document.getElementById('input');
        const output = document.getElementById('output');
        let   timer;

        
        // 初始化自动发音的状态并储存到localStorage
        let is_auto_pronunciation = localStorage.getItem('is_auto_pronunciation');
        if (!is_auto_pronunciation) {
            is_auto_pronunciation = "true" //默认自动发音
            localStorage.setItem('is_auto_pronunciation', is_auto_pronunciation)
        }
        

        input.oninput = function(ev) {
            // 减少不必要的请求
            if (timer) {
                clearTimeout(timer);
            }
            timer = setTimeout(() => {
                translateFun(); // 正在输入时的翻译不需要发音
            }, 1500);
        };

        translate.onclick = function () {
            translateFun().then(result => {
                pronunciation(result.speakUrl); // 需要发音
            });
        };

        function changePronunciationBtnText(){
            if (is_auto_pronunciation === 'true') {
                auto_pronunciation.textContent = '自动发音: 开';
                auto_pronunciation.style.backgroundColor = 'rgb(50, 226, 203)';
            } else {
                auto_pronunciation.textContent = '自动发音: 关';
                auto_pronunciation.style.backgroundColor = 'rgb(169, 169, 169)';
            }
        }
        changePronunciationBtnText();

        // 自动翻译的开关
        auto_pronunciation.onclick = function () {
            if (is_auto_pronunciation === 'true') {
                is_auto_pronunciation = 'false'
            } else {
                is_auto_pronunciation = 'true'
            }
            localStorage.setItem('is_auto_pronunciation', is_auto_pronunciation)
            changePronunciationBtnText()
        };

        async function translateFun() {
            let result = await send(input.value);
            if (!result) return {};
            // console.log(result);
            // console.log(result.speakUrl); // 翻译前的语音
            // console.log(result.tSpeakUrl); // 翻译后的语音

            if (result.basic && result.basic.explains) {
                let value = "";
                result.basic.explains.forEach(element => {
                    value += element + '\n'; //让其换行
                });
                output.value = value;
            } else if (result.translation) {
                output.value = result.translation;
            } else {
                output.value = "错误: 没有返回翻译结果!";
            }

            return result;
        };

        function pronunciation(speakUrl) {
            if (is_auto_pronunciation === 'true' && speakUrl) {
                let audio = document.createElement('audio');
                audio.src = speakUrl;
                audio.hidden = true;
                audio.play();
                audio = null;
            }
        }

       // from和to可以指定翻译语言,设置Auto为自动检测
        async function send(q, from = 'Auto', to = 'Auto') {
            if (!q) return;
            let result = null;
            await $.ajax({
                url: 'https://aidemo.youdao.com/trans',
                type: 'post',
                dataType: 'json',
                data: {
                    q,
                    from,
                    to,
                },
                success(data) {
                    result = data;
                },
                error() {alert('翻译出错了');}
            });
            return result;
        }

jquery.js就直接下载jQuery的源码, 然后重命名为jquery.js就可以了

manifest.json文件内容:

{
//插件名
  "name": "zp translate",
//版本号
  "version": "1.0",
//mainfest版本
  "manifest_version": 2,
//描述
  "description": "翻译工具",
//插件图标,128代表分辨率128*128,填最高的就行了,因为浏览器会自动调整的
  "icons": {
    "128": "icon.png"
  },
//背景html,就是点击插件图标后出现的框框
  "background": {
    "page": "index.html"
  },
//要加载的资源,如果html里需要引入js的话,请务必写上,我这里写的是相对路径
  "browser_action": {
    "default_title": "",
    "default_icon": "icon.png",
    "default_popup": "index.html"
  },
  "web_accessible_resources": [
    "index.js",
    "jquery.js"
  ],
//这是权限,意思就是你在哪个网页下可以访问的这个插件
  "permissions": [
    "http://*/*",
    "https://*/*"
  ]
}

接着把这5个文件放在一个文件夹下, 然后在Chrome里找到扩展程序:

在扩展程序里的右上角打开"开发者模式", 然后在左上角点击"加载已解压的扩展程序"

然后选择含有那5个文件的文件夹, 最后点击"选择文件夹"就OK了:

最后可以看到扩展程序里多了个"zp translate", 扩展程序的名字可以在manifest.json文件里修改

页面的右上角也多了个小图标

 

 点击小图标就可以看到扩展程序的界面了~

 

 查看英文文档时也可以翻译不认识的单词和不太理解的句子:

最好还是要把英语学好O(∩_∩)O哈哈~

猜你喜欢

转载自www.cnblogs.com/zp106/p/12700114.html