3

嗨,我正在开发一个 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>

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

4

1 回答 1

4

首先Google Translate API是现在的付费服务。要使用Google Translate API您需要获取一个API keyfrom ,您可以从这里Google获取更多信息。在你得到一个你应该像API keyurl

"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"  
  }
}

谷歌翻译 API 不再免费翻译 API 常见问题解答

于 2012-11-14T21:10:26.177 回答