Issue with the loading of Firebase in Chrome extension's background script is inconsistent

I am currently working on developing a Chrome extension that utilizes Google Firebase for authentication. In my project, I am employing webpack for building purposes, with Firebase being utilized in the background script.

However, during the initial initialization or when the script is inactive, Firebase sometimes returns null for the user and requires some time to fetch the current user data before returning it.

My main query revolves around how to efficiently load Firebase first and then make the request to avoid receiving null values?

Highlighted below are snippets from my code:

const getUser = async (): Promise<firebase.User> =>
    new Promise((resolve, reject) => {
      chrome.runtime.sendMessage(
        { message: MESSAGES.getCurrentUser },
        (user: firebase.User) => {
          if (user) resolve(user);
          reject();
        }
      );
    });

Furthermore, looking into the background script:

import firebase from "firebase/app";
import "firebase/auth";

firebase.initializeApp(firebaseConfig);

chrome.runtime.onMessage.addListener(
  (request: Request, sender, sendResponse) => {
    switch (message) {
      case MESSAGES.logOut:
        logOut(sendResponse);
        break;
      case MESSAGES.getCurrentUser:
        getCurrentUser(sendResponse);
        break;
        break;
    }
    return true;
  }
);

const getCurrentUser = async (sendResponse: (response?: any) => void) => {
  
  const user = await firebase.auth().currentUser;
  sendResponse(user);
};

Lastly, here's a glimpse of my manifest file:

{
  "short_name": "",
  "name": "",
  "manifest_version": 3,
  "version": "0.2.0",
  "icons": {
    "16": "logo192.png",
    "48": "logo192.png",
    "128": "logo192.png"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "permissions": ["activeTab", "storage", "identity", "downloads"],
  "options_page": "options.html",

  "background": {
    "service_worker": "background.js"
  },

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

Answer №1

After conducting extensive research, it was discovered that Chrome automatically shuts down the background script when not in use. Upon reactivation of the background script, Firebase is loaded from scratch, resulting in a null return for the current user's tokens. Additional logic has been implemented to address this issue.

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

Monitoring the loading progress of multiple files using Three JS

Just starting out with Three JS and I'm on a mission to create a loading screen that displays the progress of assets being loaded for a scene. I have a total of 7 different types of assets, including: 4 GLB files 2 Texture files And 1 Obj file Acco ...

Encountering TypeScript errors when trying to reference Angular2 within a Gulp setup

The issue at hand is: [11:16:06] TypeScript: 103 semantic errors [11:16:06] TypeScript: emit succeeded (with errors) I am currently using node v5.7.0 and npm 3.6.0 gulp -v: [11:26:58] Requiring external module babel-register [11:26:58] CLI version 3.9 ...

React is nowhere to be seen

index.js: import react from 'react'; import {render} from 'react-dom'; render( <h1>Hello World!</h1>, document.getElementById('root') ); package.json: { "name": "", "version": "1.0.0", "descriptio ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

The Azure GraphQL serverless function encountering an issue with the Cosmos DB connection, displaying an

After developing a serverless GraphQL API function using Azure functions and connecting it to Cosmos DB, I have encountered an issue with "Invalid URL" that has been puzzling me for a week. Despite running the graphql function locally without any problems, ...

State array is being updated

In my main container, I am setting a context for its children : import React, {useRef, useEffect, useState, ReactNode, createContext, useContext} from 'react'; import Provider from "./Provider"; import Consumer from "./Consumer&quo ...

Converting TypeScript query string values into GUIDs

I'm currently working on a project that requires me to retrieve a string value (GUID) and convert it into a GUID. The query string format is already in GUID, but when getting the value from the query string using AngularJS and TypeScript, it returns ...

Angular 2 and SystemJS: Dealing with the Challenge of Circular Dependencies

I have been struggling with a problem that seems to stem from a circular dependency. Despite conducting thorough research, I have not been able to find a suitable solution. It appears to be similar to the issue discussed here: TypeError: b is undefined in ...

Dealing with Error TS2769 in Visual Studio Code when passing props to a custom component in Vue 2 with Typescript

I've encountered an issue with a Vue JS component that involves passing a custom prop. I am utilizing the Vue Options API without utilizing the class component syntax. Whenever I pass ANY prop to my custom component the-header, I receive an error sta ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

What is the best way to shorten text in Angular?

I am looking to display smaller text on my website. I have considered creating a custom pipe to truncate strings, but in my situation it's not applicable. Here's what I'm dealing with: <p [innerHTML]="aboutUs"></p> Due to t ...

The issue arose as a result of a SQLITE_ERROR, specifically mentioning that the Users table does not exist. However, the model has been

Greetings! I am currently facing an issue while trying to integrate the "sequelize-typescript" library into my Express.JS REST API that I developed using Dependency Injection. The error I am encountering is: SQLite Error: no such table: Users Below is th ...

The type 'function that takes in a CustomEvent and returns void' cannot be assigned to a parameter of type 'EventListenerOrEventListenerObject'

When I upgraded from TypeScript version 2.5.3 to 2.6.1, my custom event setup started giving me an error. window.addEventListener('OnRewards', (e: CustomEvent) => { // my code here }) [ts] Argument of type '(e: CustomEvent) => ...

The error message "ReferenceError: window is not defined in Angular Universal" indicates

Currently, I'm utilizing Angular 10 and undergoing the process of incorporating SSR into my project. Upon executing the npm run serve:ssr, I encounter the following error: ReferenceError: window is not defined After conducting a search online, the r ...

Issue encountered with UglifyJs - Unexpected token: title (Subject)

My attempt to deploy my initial Angular application is not going smoothly. The build process fails and the error message I'm encountering states: ERROR in vendor.809dd4effe018f6b3d20.bundle.js from UglifyJs Unexpected token: name (Subject) [vendo ...

Don't forget to include the line 'import "reflect-metadata"' at the beginning of your entry point for Jest tests

As I work on developing an application using dependency injection with tsyringe, I came across a case where a service receives the repository as a dependency. Here is an example: import { injectable, inject } from 'tsyringe' import IAuthorsRepos ...

Overriding the 'first' attribute in PrimeNG's lazy table when implementing filtering

I encountered an issue while attempting to set up a primeNG table using query parameters. For example, when accessing , the data displayed should pertain to "Joe" and start at the 20th entry. To handle the large volume of data my backend can provide, lazy ...

What is the most efficient method to retrieve an API in Angular?

Recently, I dedicated some time to a personal Angular project. While working on it, I decided to experiment with making an API call to PokeAPI in order to retrieve the .svg image of a Pokemon along with its name. After successfully implementing this featur ...

Generating a fresh instance of input value in Angular2

In the hierarchy of components, I have a grand parent component where I am passing the "selectedValue" to the parent component like so: @Component({ selector: 'grand-parent', template: '<parent [details]="selectedValue" ></par ...

Select information from an array and store it within an object

I want to extract all objects from an array and combine them into a single object. Here is the current array data: userData = [ {"key":"firstName","checked":true}, {"key":"lastName","checked":true ...