Develop a Google browser plug-in (extension program) with translation function

I searched the Chrome web store and did n’t find the translation extension I wanted (the results of the translation are not satisfactory), so I plan to write one myself.

Extension program renderings:

 

 

 

The entire extension has only 5 files

 

 

 

icon.png is the icon of the extension, which is the small icon in the upper right corner of the rendering of the extension.

 

index.html is the main page of the extension. It can also be opened and run directly on the browser, but it will have a single tab page. After making the browser extension, it can be run on any tab page, which is much more convenient!

 

index.js is a JavaScript file that index.html needs to introduce.

 

jquery.js is the source code of jQuery, mainly used to send ajax requests, too lazy to use their own package.

 

manifest.json is the key file that turns the page into an extension. This is an indispensable file for a Chrome plug-in. It is used to configure all configuration related to the plug-in and must be placed in the root directory.

 

 

The translation function uses the interface of NetEase Youdao Dictionary. The translation result of NetEase Youdao Dictionary is still very satisfactory.

 

HTML and JS file content is relatively simple, I will directly paste the code.

index.html file content:

<!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 file content:

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

        
        // Initialize the automatic pronunciation state and store it in localStorage 
        let is_auto_pronunciation = localStorage.getItem ('is_auto_pronunciation' );
         if (! is_auto_pronunciation) { 
            is_auto_pronunciation = "true" // The default automatic pronunciation 
            localStorage.setItem ('is_auto_pronunciation', is_auto_pronunciation) 
        } 
        

        input.oninput = function (ev) {
             // Reduce unnecessary requests 
            if (timer) { 
                clearTimeout (timer); 
            } 
            timer = setTimeout (() => { 
                translateFun (); // When inputting Translation does not require pronunciation 
            }, 1500 ); 
        }; 

        translate.onclick = function () { 
            translateFun (). Then (result => { 
                pronunciation (result.speakUrl); // need pronunciation
             });
        };

        function changePronunciationBtnText () {
             if (is_auto_pronunciation === 'true' ) { 
                auto_pronunciation.textContent = 'Automatic pronunciation: on' ; 
                auto_pronunciation.style.backgroundColor = 'rgb (50, 226, 203)' ; 
            } else { 
                auto_pronunciation.textContent = 'Automatic pronunciation: off' ; 
                auto_pronunciation.style.backgroundColor = 'rgb (169, 169, 169)' ; 
            } 
        } 
        changePronunciationBtnText (); 

        // Automatic translation switch 
        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); // voice before translation 
            // console.log (result.tSpeakUrl); // voice after translation 

            if (result. basic && result.basic.explains) { 
                let value = "" ; 
                result.basic.explains.forEach (element => { 
                    value + = element + '\ n'; // let it wrap) 
                }); 
                output.value = value ; 
            } else  if (result.translation) { 
                output.value = result.translation; 
            }else { 
                output.value = "Error: No translation result returned!" ; 
            } 

            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 and to can specify the translation language, set Auto to automatic detection
        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 ( 'Translation error occurred' );} 
            }); 
            return result; 
        }

 

Download the source code of jQuery directly from jquery.js, and then rename it to jquery.js.

 

manifest.json file content:

{
 // plug-in name 
  "name": "zp translate" ,
 // version number 
  "version": "1.0" ,
 // mainfest version 
  "manifest_version": 2 ,
 // description 
  "description": "translation tool" ,
 // Plug-in icon, 128 means the resolution is 128 * 128, fill in the highest one, because the browser will automatically adjust the 
  "icons" : {
     "128": "icon.png" 
  }, 
// Background html, just click the plug-in icon The appearing frame 
  "background" : {
     "page": "index.html" 
  }, 
// The resource to be loaded, if you need to introduce js in HTML, please be sure to write it, I am writing here the relative path 
  "browser_action": {
    "default_title": "",
    "default_icon": "icon.png" ,
     "default_popup": "index.html" 
  },
   "web_accessible_resources" : [
     "index.js" ,
     "jquery.js" 
  ], 
// This is the permission, meaning where you are The plugin 
  "permissions" that can be accessed under the web page : [
     "http: // * / *" ,
     "https: // * / *" 
  ] 
}

 

 

Then put these 5 files in a folder, and then find the extension in Chrome:

 

 

 

Open "Developer Mode" in the upper right corner of the extension, and then click "Load uncompressed extension" in the upper left corner

 

 

 

Then select the folder containing those 5 files, and finally click "Select Folder" to be OK:

Finally, you can see that there is a "zp translate" in the extension, and the name of the extension can be modified in the manifest.json file

 

 

There is also a small icon in the upper right corner of the page

 

 

 Click the small icon to see the interface of the extension program ~

 

 

 When viewing English documents, you can also translate unrecognized words and sentences that are not well understood:

 

 

It is best to learn English well O (∩_∩) O haha ​​~

 

Guess you like

Origin www.cnblogs.com/zp106/p/12700114.html