您好,我正在开发 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>
但它不起作用?
我的问题在哪里?
感谢您的建议。
最佳答案
首先 Google Translate API
是一个 paid service现在。要使用 Google Translate API
,您需要从 Google
获取一个 API key
,您可以从 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()
使用以下请求(使用浏览器地址栏中的有效 key )
"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"
}
}
关于javascript - 使用谷歌翻译开发谷歌浏览器扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13386637/