Wednesday, March 10, 2010

Firefox extension programming: put an icon on the status bar


To better understand this article, you should have the basic knowledge of building a Firefox extension. You can refer to my another post Learn how to create a Firefox extension in 10 minutes if needed.

To put an icon on the status bar of Firefox, we first need to "overlay" the status bar in our main *.xul file. Let us name it "overlay.xul":
   <overlay ...

      <script src="chrome://our_extension/content/our_extension.js" />

      <statusbar id="status-bar">
         <statusbarpanel id="ourPanel">
            <image id="ourIcon" />
         </statusbarpanel>
      </statusbar>

   </overlay>
The Firefox status bar has an element name of "statusbar" and an ID of "status-bar". As you can see, we add our own statusbarpanel with the ID of "ourPanel". Inside the panel, we add an image holder "ourIcon". When we change the attribute of "ourIcon", we can display an icon on the status bar. In our example, we apply the image via the list-style-image style property.

You may have noticed that we add a "script" element before the "statusbar" element. It inserts our main JavaScript "our_extension.js" which locates under the "content" directory.

We want to create two icons so that when the user clicks on the icon, it can switch to show the other one. These icons should be in PNG format. We name these two icons iconGreen.png and iconGrey.png, and put them under the "chrome://our_extension/skin/" directory.

Next, we create a CSS (Cascading Style Sheets) file "overlay.css" under the same directory. The CSS file tells where the icons are:
   #ourIcon[value="green"]
   {
       list-style-image: url(chrome://our_extension/skin/iconGreen.png);
   }

   #ourIcon[value="grey"]
   {
       list-style-image: url(chrome://our_extension/skin/iconGrey.png);
   }
We then need to include the style sheet in our "overlay.xul" in the beginning:
   <?xml version="1.0"?>
   <?xml-stylesheet href="chrome://our_extension/skin/overlay.css" type="text/css"?>
Now we are ready to apply the different icon to the "image" element in "overlay.xul" by setting a "value" attribute to it. We can do this in the main JavaScript "our_extension.js":
   var theIcon = document.getElementById("ourIcon");
   if (theIcon)
      theIcon.setAttribute("value", "green");  // or set to "grey"
The icon is now showing up on the status bar. But it is not so useful yet. We could add event listener to it or add a context menu to make it useful.

To see a live example, check out my extension Take A Break.

No comments:

 
Get This <