我正在尝试制作一个使用 Google Cloud Translation API 的 Chrome 扩展程序.我遵循了 Google 翻译和 developing Chrome extensions 文档中许多不同页面上的一系列说明。但我仍然不知道如何在浏览器中实际使用 API。
我走得最远的是跟随 Quickstart guide 的一部分在其中创建服务帐户,获取服务帐户 key 文件(作为 .json 文件下载),安装并初始化 Google SDK,将 GOOGLE_APPLICATION_CREDENTIALS
环境变量设置为服务帐户 JSON key 的路径文件,然后使用 gcloud auth application-default print-access-token
发出 curl
请求,以获取要作为请求 header 的一部分输入的访问 token :“授权: Bearer(此处为 token )”。以这种方式成功检索到翻译。
但在扩展环境中,您不能运行 gcloud
这样的命令,因此它不起作用。我能够使用 gcloud
命令手动检索访问 token ,然后将其作为请求 header 的一部分粘贴到我的 javascript 代码中(例如 xmlHttpRequest.setRequestHeader('Authorization', 'Bearer ya29.c.Elr6BRuTfOtherRandomLetters');
)。但是该访问 token 会在 60 分钟后过期,因此无法持续工作。
我还尝试使用 identity.getAuthToken方法(按照文档说明的方式更新 manifest.json
中的内容后),但这没有用。使用我的服务帐户客户端 ID 作为 manifest.json
中 oauth2
下的 client_id
导致 identity 出现“无效客户端 ID”错误.getAuthToken
。另一方面,从 Google 控制台生成 OAuth2 客户端 ID,并使用 myoauth2clientid.apps.googleusercontent.com
作为 oauth2
下的 client_id
和["https://www.googleapis.com/auth/cloud-translation", "https://www.googleapis.com/auth/cloud-platform"]
作为 范围
导致 oauth2
下的 identity.getAuthToken
出现“OAuth2 not granted or revoked”错误。
从 Google 控制台页面生成一个 API key ,并将其直接用作我的翻译查询的 key
参数,甚至都不起作用:我收到了“请求缺少有效的 API key 。”错误。
我这里真的是一头雾水。任何帮助都会很棒。
最佳答案
我(第一次发布者)也经历了与您相同的步骤,但在@magicnumber 的回答的帮助下,我想出了一个解决方案,使用 APIkey 而不是在我的 Chrome 扩展中翻译文本(从任何语言到英语)服务帐户 key 文件。
首先创建一个翻译函数(我在这里使用了 Async -> Await 模式):
async function translate(strSourceText,strApiKey)
{
var url = `https://translation.googleapis.com/language/translate/v2?key=${strApiKey}`
let response = await fetch(url, {
method: 'POST',
headers : {
'Content-Type': 'application/json',
},
body: JSON.stringify({
target: "en",
format: "text",
q: strSourceText
}),
});
let data = await response.json()
return data;
}
然后调用将返回一个 promise 的异步函数,例如:
query="כלב" //Hebrew word for dog 🐶
translate(query, "YOURVALIDAPIKEYGOESHERE")
.then(response => console.log(response.data))
.catch(reason => console.log(reason.message));
来自 Google Translation API 的响应应如下所示:
{
"data": {
"translations": [
{
"translatedText": "Dog",
"detectedSourceLanguage": "iw"
}
]
}
}
最后,为了避免违反内容安全策略,在我的例子中,我必须将翻译 API 域添加到我扩展程序的 manifest.json 文件中的权限 key :
"permissions": ["https://translation.googleapis.com/language/translate/v2/*"],
关于javascript - 如何在浏览器中获取 Google Cloud Translation API 的身份验证 token (chrome 扩展),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51904999/