I have my utility class, where I calculate how many text analysis a user made. Once a user performs text analysis, I send a message to my popup.js UI, where I need to update the corresponding number.
Here is my function in my business_logic.js file:
performTextChecking(text) {
const self = this; // Save a reference to 'this' for use inside the callback function
return new Promise((resolve, reject) => {
self.retrieveTextCheckings((textCheckings) => {
self.textCheckings = textCheckings;
if (self.hasSubscription || self.textCheckings < self.monthlyLimit) {
// Perform the text checking
self.textCheckings++;
console.log('textCheckings in performTextChecking:', self.textCheckings);
// Send message to popup.js to update the UI
chrome.runtime.sendMessage({ action: 'updateCredits', credits: self.textCheckings });
// Update the stored text checkings count in local storage
chrome.storage.local.set({ textCheckings: self.textCheckings }, () => {
chrome.storage.local.get('textCheckings', (result) => {
console.log('textCheckings in performTextChecking (after set):', result.textCheckings);
});
// Send the text to the server and return the result
self.sendTextToServer(text)
.then(resultText => {
resolve(resultText);
})
.catch(error => {
console.error('Text checking failed:', error);
resolve(null);
});
});
} else {
// Set textCheckings for test purposes
self.textCheckings = 0;
chrome.storage.local.set({ textCheckings: self.textCheckings }, () => {
resolve(null);
});
// Send message to popup.js to update the UI
chrome.runtime.sendMessage({ action: 'updateCredits', credits: self.textCheckings });
// Prompt the user to subscribe
self.showSubscriptionPopup();
}
});
});
}
So I send chrome.runtime.sendMessage({ action: 'updateCredits', credits: self.textCheckings });
to my UI to update it accordingly.
In my popup.js file I have the following listener:
// Listen for messages from the background script
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === 'updateCredits') {
const creditsCountElement = document.getElementById('creditsCount');
console.log('creditsCountElement in popup.js:', request.credits);
creditsCountElement.textContent = request.credits;
}
});
However, my UI is not being updated. Moreover, I don't see that my listener in popup.js is not being called at all. I think that the message is not being sent properly from business_logic.js. What can I resolve that?
Here is my manifest file:
{
....
"browser_action": {
"default_popup": "popup/popup.html"
},
"permissions": [
"http://*/",
"https://*/",
"contextMenus",
"activeTab",
"browser_action",
"storage"
],
"icons": {
"16": "images/logo.png",
"48": "images/logo.png",
"128": "images/logo.png"
},
"background": {
"scripts": ["background.js", "server/business_logic.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>", "https://docs.google.com/*", "https://www.linkedin.com/*"],
"js": ["bottom_button/bottom_button.js", "server/business_logic.js"]
}
]
}