I want to send a message to content.js from background.js when the user navigates on the page or reloads. Therefore I am using chrome.tabs.onUpdated.addListener function.
To check if my user is navigating on my page I use changeInfo.url and check if he is on that page. The problem is that whenever I use it in an if statement, the sendMessage function is not called and therefore, the listener in the content.js is not calling the function to update the DOM (updateTweets).
background.js
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
chrome.storage.sync.get(["nickname", "stringInNickname", "username", "keyWords"], function (data) {
if (changeInfo.url !== undefined && changeInfo.url.includes("somewebsite.com/page")) {
chrome.tabs.sendMessage(tabId, data);
}
});
});
content.js
function setEventListeners() {
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
data.unwantedNicknames = request.nickname.split(",").filter((val) => val != "");
data.unwantedStringInNickname = request.stringInNickname.split(",").filter((val) => val != "");
data.unwantedUsernames = request.username.split(",").filter((val) => val != "");
data.unwantedKeyWords = request.keyWords.split(",").filter((val) => val != "");
updateTweets();
});
}
manifest.js
{
"manifest_version": 2,
"name": "extension",
"version": "1.0",
"content_scripts": [
{
"matches": ["*://*.somewebsite/page/*"],
"js": ["./content.js"]
}
],
"permissions": ["storage", "tabs"],
"browser_action": {
"default_icon": "popup16.png",
"default_popup": "panel/panel.html",
"default_title": "My popup!"
},
"background": {
"scripts": ["background.js"]
}
}
I tried working around the problem and setting a timeout function for both updateTweets() and sendMessage() and it worked. I don't understand why the sendMessage is not being called. Previously it worked without any if statements, I even tried with changeInfo.status === "complete" and it worked. Does it have to do something with the callbacks?
Even if I just do if(changeInfo.url), something that I saw in another stack questions, the sendMessage is not called. But if I have some conosle logs in the if statement where sendMessage is they get logged in the console but sendMessage isn't called.
Also, chageInfo doesn't always return url in the object, maybe that's the problem, but I use the if statement to check if it is defined.
I could solve it with changeInfo.status and make a few unneeded calls of the updateTweets function, but I wan't to make it as right as possible. I'm pretty much struggling with this one the whole day.
I don't know why it is not working as expected