Reputation: 35
I'm building a simple extension that requires the default_icon to change depending if a JS variable exists in a page or not. It's as simple as that, at least this feature.
I managed to change the picture on each page load with this condition, but I would like to go further and have the picture changed for all loaded tabs in the user's browser, whenever the user changes the tabs he's focusing on. I'm having trouble trying to have the default_icon be changed for the active tab only.
Would anyone know how I should proceed to make it so ? (I'm still a beginner in writing Chrome Extensions)
My content.js :
if (test == "OK") {
// Setting OK Icon
chrome.runtime.sendMessage({"message": "Existing"});
}
else if (test == "NOK") {
// Setting NOK Icon
chrome.runtime.sendMessage({"message": "Not existing"});
}
My background.js :
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "Existing" ) {
chrome.browserAction.setIcon({path:"OKicon.png"});
}
if( request.message === "Not Existing" ) {
chrome.browserAction.setIcon({path:"NOKicon.png"});
}
}
);
Upvotes: 0
Views: 1990
Reputation: 77482
Well, you should take a look at the chrome.browserAction.setIcon
documentation.
integer (optional)
tabId
Limits the change to when a particular tab is selected. Automatically resets when the tab is closed.
Just what was needed! Now, the tab ID is reported in the sender
parameter:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "Existing" ) {
chrome.browserAction.setIcon({
path:"OKicon.png",
tabId: sender.tab.id
});
}
if( request.message === "Not Existing" ) {
chrome.browserAction.setIcon({
path:"NOKicon.png",
tabId: sender.tab.id
});
}
}
);
Upvotes: 4
Reputation: 1556
You're basically there. All you would need to do is wrap the logic you have in the content script as a callback to the window focus
event.
window.onfocus = function(){
if (test == "OK") {
// Setting OK Icon
chrome.runtime.sendMessage({"message": "Existing"});
} else {
// Setting NOK Icon
chrome.runtime.sendMessage({"message": "Not existing"});
}
}
When user changes focus the background
script will receive the runtime message from the context
script and change the extension icon accordingly.
Upvotes: 0