Zeynel Zeynel - 1 year ago 167
Javascript Question

How to animate chrome extension icon in a callback function?

This is a follow up to my previous question about using

to post to my bookmarking app. When I receive the
status 200 OK
I want to indicate somehow with a change in the extension icon that the request was successful. I created another icon
with reverse colors and I am trying to make the new icon replace the original icon and fade into original icon. I understand that this will be inside my callback function but I don't understand how? Here's my
. Thanks!

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {
tabId = tab.id;
tabUrl = tab.url
tabTitle = tab.title

var formData = new FormData();
formData.append("url", tabUrl);
formData.append("title", tabTitle);
formData.append("pitch", "this is a note");

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4) {
if (xhr.status == 200)
console.log("request 200-OK")
console.log("Error", xhr.statusText);


Code adapted from eduardocereto's answer but
is not working properly:

if (xhr.readyState == 4 && xhr.status == 200) {
console.log("request 200-OK");
//chrome.browserAction.setIcon({path: '/success_icon.png'});
chrome.browserAction.setBadgeText ( { text: "done" } );

function resetBadge() {
setTimeout (chrome.browserAction.setBadgeText( { text: "" } ), 10000);


Answer Source

To change the icon dynamically you can call:

chrome.browserAction.setIcon({path: '/path/img/success_icon.png'})

To create the fade effect would not be so easy, but you can use a <canvas> element instead of static image to set the Icon. Then you can probably animate the canvas the way you want.

Checkout this article on how to load an image into the canvas and change it's opacity:

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

API Reference: http://code.google.com/chrome/extensions/browserAction.html#method-setIcon

To use the setBadgeText with setTimeout you should do this:

chrome.browserAction.setBadgeText ( { text: "done" } );
setTimeout(function () {
    chrome.browserAction.setBadgeText( { text: "" } );
}, 1000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download