Guide on implementing the onSignInChanged event handler in a Chrome extension for Gmail

Here is a glimpse of the code from my Google Chrome extension:

Manifest:

"content_scripts": [
  {
   "matches": [
   "https://mail.google.com/*",
   "https://inbox.google.com/*"
 ],
 "js": ["js/jquery-3.2.1.min.js", "js/content.js"],
 "css": ["css/custom.css"],
 "run_at": "document_end"
 }
],
"background":{
  "scripts": ["js/background.js"],
  "persistent": true
},
"permissions": [
  "https://mail.google.com/",
  "https://inbox.google.com/",
  "https://accounts.google.com/*",
  "identity",
  "identity.email",
  "storage"
],
"oauth2":{
  "client_id": "xxx",
  "scopes": [
    "profile",
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/contacts.readonly",
    "https://www.googleapis.com/auth/plus.login",
    "https://www.googleapis.com/auth/userinfo.profile",
     "https://www.googleapis.com/auth/userinfo.email"
  ]
}

background.js

// Retrieving Google OAuth Token
chrome.identity.getAuthToken({
  interactive: true
}, function(token) {
  if (chrome.runtime.lastError) {
    console.log(chrome.runtime.lastError.message);
    alert(chrome.runtime.lastError.message);
    return;
  }
  console.log(token);
  currentSessionAccessToken = token;
  var x = new XMLHttpRequest();
  x.open('GET',
    'https://www.googleapis.com/oauth2/v2/userinfo?alt=json&access_token=' + token
  );
  x.onload = function() {
    console.log(x.response);
  };
  x.send();
});

// Registering event handler for signIn change
chrome.identity.onSignInChanged.addListener(function(accountInfo, isSignedIn){
  console.log(accountInfo);
});

However, the onSignInChanged event doesn't fire when I switch to another user. I intend to revoke the token for the previously logged-in user upon a sign-in change, generating a new token for the newly logged-in user.

Unfortunately, as the event is not triggered, my extension continues to load contacts from the previously signed-in user. I have followed Google's documentation, but I'm unsure why the event isn't firing. Is there something I might be overlooking?

Answer №1

Although the event fails to trigger, there is a solution. Verify if the user currently logged in matches the email linked to the authentication token. If they match, proceed with the application; if not, invalidate the current token, generate a new one for the logged in user, and then send the Google API request.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS - managing checkboxes and dropdownlists

When I talk about the topic of depending on checkboxes from a dropdown list, I mention that I populate my dropdown list with data from the controller: @RequestMapping(value = "/all", method = GET) public List<Warehouse> findAll(){ return warehous ...

The render props on the child component are not appearing on the screen as expected

Recently diving into React Native, I created a stateless component designed to iterate through props that contain objects with arrays of tags. The goal was to extract and display a single tag from each array item. (Refer to the console log in the screensh ...

Getting up and running with the NICE DCV SDK: A beginner's guide

Exploring the NICE DCV SDK provided by AWS has been my latest project. You can find the documentation here. However, I've hit a roadblock while trying to run the example code mentioned in the docs. My attempt to execute it on a node server resulted in ...

Tips on implementing a jQuery .load() function using an anchor tag within dynamic content

I am working on a search page where user input is taken from a form and then sent to a PHP file that makes a cURL call to an external server. The PHP file receives an array from the server, which it uses to display HTML in a "results" div on the original s ...

Utilizing a dropdown selection to trigger an IF statement in a function

I have an HTML code snippet as shown below: The value "Test" is just for my reference to ensure that the code is functioning properly :) <script> var tfa78 = document.getElementById("tfa_78").selvalue; if( tfa78 == "karte" ) { document.getEl ...

Switching from jQuery to vanilla JavaScript, iterating through each HTML tag in a loop

Here is my current jQuery code that I am looking to convert into vanilla JavaScript. var elements = []; document.querySelectorAll('*:not(script, style, iframe)').forEach(function(element) { elements.push(element); }); I have tried using d ...

Node.js console and endpoint are returning an object, but the JSON object cannot be fetched

Currently, I am working on a project for an online course where I am utilizing an NLP sentiment analysis API. Although I have made significant progress, I seem to be stuck at the final step. When I send the URL for analysis via the API call, I can see the ...

The functionality of bigvideo.js is not supported on the Opera browser

I am facing an issue with the bigvideo.js script as it does not seem to be working on the Opera browser. Do you have any suggestions for a solution? I successfully used this script in Firefox. $(function() { var BV = new $.BigVideo({useFlashForFirefo ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

When transitioning from component to page, the HTTP request fails to execute

I have created a dashboard with a component called userInfo on the homepage. This component maps through all users and displays their information. Each user has a display button next to them, which leads to the userDisplay page where the selected user&apos ...

Tips on modifying the message "Please fill out this field" in the JQuery validation plugin

Is there a way to customize the message "This field is required" in the Jquery form validation plugin to display as "このフィールドは必須です"? Changing the color of the message can be achieved using the code snippet below: <style type="tex ...

Troubleshooting the error "The 'listener' argument must be a function" in Node.js HTTP applications

I'm facing an issue resolving this error in my code. It works perfectly fine on my local environment, but once it reaches the 'http.get' call, it keeps throwing the error: "listener argument must be a function." Both Nodejs versions are iden ...

Webpack fails to resolve paths provided by a JavaScript variable

I am currently developing an application using vue and ionic, but I have encountered an issue with loading assets as the paths are not resolving correctly. <template> <div id="index"> <img :src="image.src" v-for="image in image ...

What is the process of building a service in AngularJS?

I have written this code using a service in angular.js. Upon running the code, I encountered an error Uncaught Error: [ng:areq]. </ons-toolbar> <div ng-controller="testAppController"> Search: <input ng-model="query" type=" ...

Tips for Running a Unique Code the First Time the $.each() Function is Used

During the initial iteration of my $.each() loop, I run a unique code. However, for all subsequent iterations until the end of the loop, my code remains the same. ...

Using JSON to interact with Response APIs across various programming languages

I am currently facing an issue while attempting to return a response from my API in the language selected from the header using: Accept-Language: es-MX or Accept-Language: en-US function getLanguage(req, res, next) { let lang = req.acceptsLanguages(&a ...

What could be the reason my Virtual Mongoose categories aren't appearing?

Here is the description of my post model: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PostSchema = new Schema({ text: String, image: String, author: { type: Schema.Types.ObjectId, ref: 'user&ap ...

`"Attempting to access keys of a non-object value" - Dealing with JSON and React Native`

Having trouble with React Native and JSON structure? No worries, we've all been there at some point! Don't sweat it if you're still new to React and JavaScript - we're here to help! Let's take a look at the JSON structure causing ...

Unraveling nested JSON structures with varying formats in Javascript or Jquery: Step-by-step guide

var cart = [ { "Items": "", "category": "", "contents": [ { "Apple iPhone": "222", "French": "Bounjour", "id": 1234, "icon": "/images/bg.jpg", "callback": "use()", "pricetag":"false" } ] }, { "Items": "No 2" ...

Looking for an improved, tidier, or more efficient alternative to PHP Random Text?

Is there a more efficient way to generate random text other than using the random_text function in PHP? I'm interested in a method that is quick to render and light on server resources for faster page loading. Should I consider alternatives like Javas ...