简体   繁体   中英

Chrome Extension - Change default_icon for active tab only

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"});
    }
  }
);

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
        });
    }
  }
);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM