使用Google翻译开发Google Chrome扩展程序

时间:2012-11-14 20:18:39

标签: javascript json rest google-chrome-extension

嗨,我正在开发Google Chrome扩展程序:
这是一个使用Google翻译API的字典,
当用户选择页面上的文字时,我想要一个弹出窗口显示并显示所选的文字定义,

我在js文件中有这段代码:

var req = new XMLHttpRequest();
req.open(
    "GET",
    "https://www.googleapis.com/language/translate/v2?" +
    "format=html" +
    "q=" + get_text_selection() + // Source Text
"source=en&" + // Source Language
"target=fa&" + // Target Language
true);
req.send(null);

function get_text_selection() {

    if (window.getSelection)

    return window.getSelection();

    if (document.getSelection)

    return document.getSelection();

    if (document.selection)

    return document.selection.createRange().text;

    return '';

}

和我的Manifest.json文件中的代码:

{
  "name": "Google Translator",
  "version": "1.0",
  "manifest_version": 2,
  "description": "This Extention helps you to translate text in your page",
  "browser_action": {
    "default_icon": "Dictionary-Book-icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [ "http://*/*", "https://*/*", "tabs" ]
}

和我的html文件中的代码:

<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
      body {
        min-width:357px;
        overflow-x:hidden;
      }

    </style>
    <!-- JavaScript and HTML must be in separate files for security. -->
    <script src="popup.js"></script>
  </head>
  <body>
  </body>
</html>

但它不起作用?
我的问题在哪里?
谢谢你的建议。

1 个答案:

答案 0 :(得分:3)

首先,Google Translate API现在是paid service。要使用Google Translate API,您需要从API key获得Google,您可以从here获取更多信息。收到API key后,url应该是

"https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=fa&q=Hello%20world" // "Hello world" is query here

你的情况

"https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY" + "&format=html" + "&source=en" +"&target=fa" + "&q=" + get_text_selection()

使用以下请求(使用浏览器地址栏中的有效密钥)

"https://www.googleapis.com/language/translate/v2?key=my_valid_key&format=html&q=home&source=en&target=fa" // I've replaced my key with my_valid_key

我有这个结果

{  "error": {   "errors": [    {
    "domain": "usageLimits",
    "reason": "dailyLimitExceeded",
    "message": "Daily Limit Exceeded"    }   ],
    "code": 403,   
    "message": "Daily Limit Exceeded"  
  }
}

Google Translate API no longer freeTranslate API FAQ