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"]
}
]
}