最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get an authentication token for Google Cloud Translation API within browser (chrome extension) - Stack Overf

programmeradmin3浏览0评论

I'm trying to make a Chrome extension that uses the Google Cloud Translation API. I followed a bunch of instructions on many different pages in the docs for Google Translate and for developing Chrome extensions but I still can't figure out how to actually use the API from within a Browser.

The farthest I've gotten was from following part of the Quickstart guide where you create a service account, get a service account key file (downloaded as a .json file), install and initialize the Google SDK, set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of the service account JSON key file, and then make a curl request using gcloud auth application-default print-access-token to get an access token to be inputted as part of the request header: "Authorization: Bearer (token here)". Successfully retrieved a translation that way.

But within the environment of an extension you can't run mands like gcloud so that doesn't work. I was able to manually retrieve an access token using the gcloud mand, and then paste that into my javascript code as part of the request header (e.g. xmlHttpRequest.setRequestHeader('Authorization', 'Bearer ya29.c.Elr6BRuTfOtherRandomLetters');). But that access token expires after 60 minutes so that doesn't sustainably work.

I also tried using the identity.getAuthToken method (after updating things in manifest.json the way the documentation says to), but that didn't work. Using my service account client ID as the client_id under oauth2 in manifest.json resulted in an "Invalid client ID" error from identity.getAuthToken. On the other hand, generating an OAuth2 Client ID from Google Console, and using myoauth2clientid.apps.googleusercontent as the client_id under oauth2 and ["", ""] as the scopes under oauth2 resulted in an "OAuth2 not granted or revoked" error from identity.getAuthToken.

Generating an API key from the Google Console page, and using that directly as the key parameter of my translation query, didn't even work: I received a "The request is missing a valid API key." error.

I am really at a loss here. Any help would be awesome.

I'm trying to make a Chrome extension that uses the Google Cloud Translation API. I followed a bunch of instructions on many different pages in the docs for Google Translate and for developing Chrome extensions but I still can't figure out how to actually use the API from within a Browser.

The farthest I've gotten was from following part of the Quickstart guide where you create a service account, get a service account key file (downloaded as a .json file), install and initialize the Google SDK, set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of the service account JSON key file, and then make a curl request using gcloud auth application-default print-access-token to get an access token to be inputted as part of the request header: "Authorization: Bearer (token here)". Successfully retrieved a translation that way.

But within the environment of an extension you can't run mands like gcloud so that doesn't work. I was able to manually retrieve an access token using the gcloud mand, and then paste that into my javascript code as part of the request header (e.g. xmlHttpRequest.setRequestHeader('Authorization', 'Bearer ya29.c.Elr6BRuTfOtherRandomLetters');). But that access token expires after 60 minutes so that doesn't sustainably work.

I also tried using the identity.getAuthToken method (after updating things in manifest.json the way the documentation says to), but that didn't work. Using my service account client ID as the client_id under oauth2 in manifest.json resulted in an "Invalid client ID" error from identity.getAuthToken. On the other hand, generating an OAuth2 Client ID from Google Console, and using myoauth2clientid.apps.googleusercontent. as the client_id under oauth2 and ["https://www.googleapis./auth/cloud-translation", "https://www.googleapis./auth/cloud-platform"] as the scopes under oauth2 resulted in an "OAuth2 not granted or revoked" error from identity.getAuthToken.

Generating an API key from the Google Console page, and using that directly as the key parameter of my translation query, didn't even work: I received a "The request is missing a valid API key." error.

I am really at a loss here. Any help would be awesome.

Share Improve this question edited Aug 19, 2018 at 14:12 Aly asked Aug 18, 2018 at 3:30 AlyAly 611 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

I (first time poster) also went through the same steps as you but with the help of @magicnumber's answer I came up with a solution to translate text (from any language to English) in my Chrome Extension using an APIkey instead of a service account key file.

First create a translate function (I used the Async -> Await pattern here):

 async function translate(strSourceText,strApiKey)
  {
    var url = `https://translation.googleapis./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;
  }

Then call the async function which will return a promise E.g.:

query="כלב" //Hebrew word for dog 

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论