Extending Firefox and Thunderbird |
Written by Mike James | |||||||
Saturday, 20 June 2009 | |||||||
Page 3 of 6
As a simple example of an extension lets add a new menu item in the Tools menu which simply pops-up an alert window that says "hello world". The Wizard creates some XUL and code that does something similar but not in the simplest way so let's create our own layout and code. First open the file firefoxOverlay.js in NotePad and change it to read: <?xml version="1.0" encoding="UTF-8"?> These three lines always start an XUL file and simply establish its type and namespace. The third line specifies the id of your overlay. There are additional "header" lines you can include in the XUL file but these are the most important. Next we can specify a file that contains JavaScript to be run when the overlay is installed. In our case this is just the overlay.js file that the Wizard created: <script src="/overlay.js"/> Now we can add lines that look a lot like HTML and define menu items, buttons, textboxes and so on. These will be added to the browser's user interface but first we have to say exactly where our new controls will be added. As already mentioned, the entire browser user interface, including any HTML pages it might be displaying forms a single huge DOM tree and all we have to do is specify the id of the node to which we want to attach our controls. <menupopup id="menu_ToolsPopup"> The new menu item has the id "helloworld-hello" and it is important that it uses a unique id to avoid conflicts within the DOM. You can add additional attributes to determine the behaviour and look of the new menu item. Setting the oncommand attribute determines the name of the function called when the user clicks the menu option. In this case it's the onMenuItem method of the helloworld object, both of which are defined in the companion JavaScript file. The next step is to write the JavaScript we need. Open the Overlay.js file in Notepad and change it to read as follows: var helloworld = { As long as you know a little JavaScript this should make sense. The first part creates a JavaScript object with two methods, onLoad and onMenuItemCommand. The onLoad function simply sets a local variable initialised to true so the other methods can check that it has been initialised and everything is loaded and ready to go. The onMenuItemCommand simply pops up an alert box with the message in it. Notice that this method has already been linked to the menu item event in the XUL file. The onLoad method, however, still needs to be linked to a suitable event. This is the job of the final line which adds the onLoad method to the list of methods that are called when the browser's "load" event fires. |
|||||||
Last Updated ( Saturday, 27 June 2009 ) |