Updating an extension button dynamically - inspiration required

tl;dr: Call it from background.js

I googled around this comment because I was trying to call a chrome.browserActions function from my content script

It's only accessible to scripts that are running as part of a chrome extension, since content_scripts are the same as client scripts you'd have to access them through the chrome.* api's

and to fix some addition headaches I had the call for setBadge text needs to look like:

chrome.browserAction.setBadgeText({text: 'ASDF'});

You can put as many characters as you want, but only 4 or so will appear. I got hung up on what the object property needed to be.


You may change the extension icon like this:

chrome.browserAction.setIcon({path: icon});

There is also a 'badge' - small box over the extension icon that shows ie. number of unread messages in gmail extension. You can manipulate it like this:

chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:"?"});

It is also possible to generate icon dynamically on a canvas element and then display it like this:

chrome.browserAction.setIcon({imageData:canvasContext.getImageData(0, 0, canvas.width,canvas.height)});

Note that you must call this from your background script, since the content script will not have permission!


You can also set a timeout to check changes on the system every x minutes, and then update de badge.

On my extension, I have an task counter called inside a notification function. Something like :

$.getJSON(
    "http://mydomain/notifications?ajax=1&callback=?",
    function(data){
        var result = data.retorno;
        if(result.length > 0){
            var totalItens = result[0].total
        } else {
            var totalItens = 0;
        }
        chrome.browserAction.setIcon({path: '19.png'});
        chrome.browserAction.setBadgeText({text:''+totalItens+''});

        for(var i=0; i<result.length; i++){

          var imagem = 'http://mydomain/myimage';
          var titulo = 'mytitle';
          var desciption = 'mydescription';

          var urlNot = 'http://mydomain/mypageOnclick';

          var not = new Notifier(urlNot);
          not.Notify(
              imagem,     // The image.
              titulo,     // The title.
              desciption  // The body.
          );

        }

    }
);