bhambu_sudhir
bhambu_sudhir

Reputation: 21

How to call Gmail Api from chrome extension?

I am getting following error while requesting Gmail api : error : code : 401 errors : Array(1) 0 : domain : "global" location : "Authorization" locationType : "header" message : "Invalid Credentials" reason : "authError" [[Prototype]] : Object length : 1 [[Prototype]] : Array(0) message : "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project." status : "UNAUTHENTICATED" background.js

 chrome.identity.getAuthToken().then(token => { 
console.log(token);

fetch('https://www.googleapis.com/gmail/v1/users/me/labels', {

method: 'POST', headers: { 'Authorization': Bearer ${token}, 'Content-Type': 'application/json' }, body: JSON.stringify({ labelListVisibility: 'labelShow', messageListVisibility: 'show', name: 'labelName' }) }).then(response => response.json())enter code here .then(data => console.log(data)) .catch(error => console.error(error));

});

Upvotes: 0

Views: 425

Answers (1)

Matheus Irineu
Matheus Irineu

Reputation: 51

Did you try adding

"oauth2": {
    "client_id": "<YOUR_CLIENT_ID>.apps.googleusercontent.com",
    "scopes": [
      "https://www.googleapis.com/auth/gmail.modify",
      "https://mail.google.com/"
    ]
  },

Having the www.googleapis.com in the "scopes" worked for me.

Also, take a look at the match patterns, I've been working with a Gmail extension and my "matches" are ://mail.google.com/

https://developer.chrome.com/docs/extensions/mv3/match_patterns/

Upvotes: 2

Related Questions