I'm new to Chrome extensions so bear with me.
I've tried many of the ways that were answered to other very similar questions but nothing seem to work.
In my manifest.json I added this code:
"content_scripts": [
{
"matches": ["http://*.website.com/*", "https://*.website.com/*"],
"js": ["icon.js"]
}
]
As far as I know this should inject the script icon.js to the websites in the "matches".
The script icon.js is only this code: chrome.runtime.sendMessage({icon:true})
therefore I expect that "icon:true" is sent as a message to my background script.
In my background.js I have this code (copied from this answer: How to dynamically change a chrome extension's icon? being fairly recent compared to others I have found):
chrome.runtime.onMessage.addListener(function(msg, sender, senResponse) => {
if(msg.value == true) {
chrome.runtime.query({active:true, windowType:"normal", currentWindow: true}, function(d) {
var tabID = d[0].id;
chrome.browserAction.setIcon({path: 'images/icon_16_red.png'});
})
}
})
As far as I understood this code should receive the message "icon:true", and change the icon of the extension.
I do not get any Error. It doesn't work either though and I cannot understand why.
I realize that there could be a much easier way to do what I'm trying to do, so feel free to say so.
Thank you!
Edit:
Thanks to @wOxxOm I managed to make my code work. I also realized that the result my code creates is not what I'm looking for and that's a big step forward!
The tweaks to my code were these:
In icon.js
chrome.runtime.sendMessage({icon:true});
Forgot the semicolon!
In the background.js
chrome.runtime.onMessage.addListener(function(msg, sender, senResponse) => {
if(msg.icon == true) {
chrome.browserAction.setIcon({path: 'images/icon_16_red.png', tabId: sender.tab.id});
}
})
Compared to the one before is way lighter.
This code works! That is as long as you have a "browser_action": {}
set in your manifest.json.
The only problem with my needs is that it'll work when you refresh the targeted website and not simply by moving to the tab where the website is already running/loaded.