開發一款有翻譯功能的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" autofocus 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文件里修改

 

 

頁面的右上角也多了個小圖標

 

 

 點擊小圖標就可以看到擴展程序的界面了~

 

 

 查看英文文檔時也可以立即在當前頁面翻譯單詞和句子, 很方便:

 

 

還可以給擴展程序設置快捷鍵, 步驟如下:

1.進入擴展程序, 點擊左上角的小圖標

 

2.點擊"鍵盤快捷鍵"

 

 3.在輸入框按快捷鍵就可以了

 

 

 

接着就可以在任何頁面按快捷鍵打開翻譯工具

 

最好還是要把英語學好~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM