2012-11-14 185 views
3

嗨,我正在开发谷歌浏览器扩展程序:
这是一个使用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

相关:http://stackoverflow.com/questions/2626859/chrome-extension-how-to-capture-selected-text-and-send-to-a-web-service。但是您还需要知道如何在活动页面和弹出窗口之间进行通信。我确信这个问题也被问到,但目前我找不到它...... – apsillers

回答

3

首先Google Translate API现在是paid service。要使用Google Translate API您需要从Google获得API key,您可以从here获取更多信息。你之后得到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" 
    } 
} 

Google Translate API no longer freeTranslate API FAQ