Changes

Jump to: navigation, search

Dive into Mozilla Modifying Firefox using an Extension Lab

11,068 bytes removed, 11:56, 14 March 2007
no edit summary
Finally, we've got all the pieces in place and can write some code.
=The 'How': the extension's code=
Now that we have the logic for our code, all that remains is to write the necessary pieces to have it get executed at the right times. When we modified the code in the tree this wasn't a concern: we assumed that code we changed in '''addTab''' would get executed whenever '''addTab''' got called. With an extension, we have to explicitly tell the browser how and when to execute our code. We do this using '''event listeners'''.
From our previous research, we know that the methods in tabbrowser cause a variety of events to get dispatched into the event system. These events move through the event system regardless of whether any code notices them--they are passive. In most cases, nothing is done in response to events. However, any developer can decide to do something in response to an event, which is what extension developers must do in order to get their code into the browser.
We need to wire our code to a number of events by [http://developer.mozilla.org/en/docs/XUL_Event_Propagation#Adding_an_Event_Listener adding event listeners]. Two of the events we know already, '''TabOpen''' and '''TabSelect'''. However, we also need to have the code to accomplish this get called in a sort of global event listener, the '''window's load event'''. We'll add code to remove our event listeners in the '''window's unload event''' too.
Question: does moving a tab break our tab position state code? Do To keep things clean we also need to update position on TabMove???    Start by creating a new extension, either by hand, or using Ted Mielczarek's wonderful wizard:  http://ted.mielczarek.org/ll write all this code/mozilla/extensionwiz/  Directory structure:  '''addtabbeside/''' content.manifest install.rdf in a custom object called '''content/AddTabBeside''' firefoxOverlay.xul overlay.js   Here is the '''content.manifest''' file:  content addtabbeside content/ overlay chrome://browser/content/browser.xul chrome://addtabbeside/content/firefoxOverlay.xul    Here is the '''install.rdf''' file for the extension: <pre> <?xml version="1.0" encoding="UTF-8"?> <RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <Description about="urn:mozilla:install-manifest"> <em:id>addtabbeside@senecac.on.ca</em:id> <em:name>Add Tab Beside</em:name> <em:version>0.1</em:version> <em:creator>David Humphrey</em:creator> <em:description>New tabs are created beside the current tab instead of at the end of the tab list.</em:description> <em:targetApplication> <Description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <!-- firefox --> <em:minVersion>2.0</em:minVersion> <em:maxVersion>3.0a3pre</em:maxVersion> <!-- trunk build Feb 27, 2007 --> </Description> </em:targetApplication> </Description> </RDF></pre>  Here is firefoxOverlay.xul: <pre> <?xml version="1.0" encoding="UTF-8"?> <overlay id="addtabbeside-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="overlay.js"/> </overlay></pre>  Load Listener code:  http://developer.mozilla.org/en/docs/Extension_Frequently_Asked_Questions#Why_doesn.27t_my_script_run_properly.3F   Reading through the rest of the '''moveTab''' method, we see that when a tab is successfully created, the '''TabOpenAddTabBeside''' event is dispatched  (see ...)  // Dispatch a new tab notification. We do this once we're // entirely done, so that things are in a consistent state // even if the event listener opens or closes tabs. var evt = document.createEvent("Events"); evt.initEvent("TabOpen", true, false); t.dispatchEvent(evt); return t; This is useful information, because it tells us that if we want to know when a tab has been created, we have to add a listener for this event.  moveTabTo http://lxr.mozilla.org/seamonkey/source/toolkit/content/widgets/tabbrowser.xml#1958  Create a file named: '''addtabbeside@senecac.on.ca''' This file should contain the full path to your extension, for example:  C:\temp\addtabbeside Now put this file in your development profile's extensions directory (NOTE: replace ''Username'' with your username and ''dev-profile'' with your development profile name):  C:\Documents and Settings\''Username''\Application Data\Mozilla\Firefox\Profiles\''dev-profile''\extensions       '''overlay.js'''
var AddTabBeside = {
onUnload: function() {
// Remove our listeners
var container = gBrowser.tabContainer;
container.removeEventListener("TabOpen", this.onTabOpen, false);
onTabSelect: function (e) {
// when When a different tab is selected, remember which one. This is
// necessary because when a new tab is created, it will get pushed
// to the end of the list, but we need to know where to put it.
};
// Insure that our code gets loaded at start-up
window.addEventListener("load", function(e) { AddTabBeside.onLoad(e); }, false);
Question: does moving a tab break our tab position state code? Do we also need to update position on TabMove???
It's one thing to say you'd like to change the browser's behaviour, but quite another to actually do it. The change you have in mind might be quite simple, in the end (ours is). But you still have to figure out where that simple code needs to go. That can be difficult. However, difficult isn't the same as impossible.
How do you begin? First, let's start at the top and find some UI notation we can search for in the code. In our case, we can focus on the various methods for creating a new tab:
* CTRL+T
* Right-Click an existing tab and select New Tab
* File > New Tab
The second and third methods are useful, as they provide us with a unique string we can search for in the code. Before we can change anything, we have to search and read existing code in order to understand where to begin--this is the standard pattern for open source and Mozilla development.
==Search 1 - finding a UI string==
We're looking for a unique string--"New Tab"==, so we'll use [http://lxr.mozilla.org LXR's] '''Text Search''' feature. Here are the results you get when you search for "New Tab":
<blockquote>http://lxr.mozilla.org/seamonkey/search?string=New+Tab</blockquote>
Lots of resultsStart by creating a new extension, many of which point to comments in the code. Howevereither by hand, the first result looks interestingor using Ted Mielczarek's wonderful wizard:
<blockquote>http://lxrted.mozillamielczarek.org/seamonkeycode/source/toolkit/locales/en-US/chrome/globalmozilla/tabbrowser.dtd#2<extensionwiz/blockquote>
Here we see the DTD file describing the key/value pairs for the en-US localized strings. Mozilla uses this technique to allow localizers to translate strings in an application into many different languages without having to change hard-coded strings in the code (you can read more about localization, DTDs, and Entities [http://developer.mozilla.org/en/docs/XUL_Tutorial:Localization here])
Looking closely at '''tabbrowser.dtd''' we see that our English string, "New Tab", has the following entityDirectory structure:
<!ENTITY '''addtabbeside/''' content.manifest install.rdf '''content/''' firefoxOverlay.xul overlay.js newTab.label "New Tab">
This is good information, because it allows us to repeat our search with an entity instead of a string, which should help us get closer to the code we're after.
==Search 2 - finding an ENTITY==Here is the '''content.manifest''' file:
Repeating the search with the '''newTab content addtabbeside content/ overlay chrome://browser/content/browser.label''' ENTITY value instead of the "New Tab" string makes a big difference--we have many fewer hitsxul chrome://addtabbeside/content/firefoxOverlay.xul
<blockquote>http://lxr.mozilla.org/seamonkey/search?string=newTab.label</blockquote>
Not surprisingly, the first result is the same DTD file (i.e., tabbrowser.dtd) we already found. The second result looks interesting, though:
<blockquote>http://lxr.mozilla.org/seamonkey/source/toolkit/content/widgets/tabbrowser.xml#80</blockquote>
Here we see is the code to generate the pop-up context menu '''install.rdf''' file for a tab (i.e., what you get when you right-click on a tab in the browser)extension:
<pre> <xul:menuitem label?xml version="&newTab1.label;0" encoding="UTF-8" accesskey?> <RDF xmlns="&newTabhttp://www.w3.accesskey;org/1999/02/22-rdf-syntax-ns#" xblxmlns:inheritsem="oncommandhttp://www.mozilla.org/2004/em-rdf#"> <Description about=onnewtab"urn:mozilla:install-manifest"> <em:id>addtabbeside@senecac.on.ca</em:id> <em:name>Add Tab Beside</em:name> <em:version>0.1</em:version> <em:creator>David Humphrey</em:creator> <em:description>New tabs are created beside the current tab instead of at the end of the tab list.</em:description> <em:targetApplication> <Description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <!-- firefox --> <em:minVersion>2.0</em:minVersion> <em:maxVersion>3.0a3pre</em:maxVersion> <!-- trunk build Feb 27, 2007 --> </Description> </em:targetApplication> </Description> </RDF></pre>
Having found the appropriate entity value, we also notice the use of a function name, '''onnewtab'''. This line of code says that the xul:menuitem will inherit the '''oncommand''' value from its parent (you can read more about XBL attribute inheritance [http://developer.mozilla.org/en/docs/XUL_Tutorial:XBL_Attribute_Inheritance here]). In other words, when this menu item is clicked, call the '''onnewtab''' function.
==Search 3 - finding a Function==Here is firefoxOverlay.xul:
Armed with this new information, we are even closer to finding the right spot to begin working<pre> <?xml version="1.0" encoding="UTF-8"?> <overlay id="addtabbeside-overlay" xmlns="http://www.mozilla. We've gone from UI string to XML ENTITY to functionorg/keymaster/gatekeeper/there.is.only.xul"> <script src="overlay. js"/> All we have to do now is find that function:</overlay></pre>
<blockquote>http://lxr.mozilla.org/seamonkey/search?string=onnewtab</blockquote>
This returns many results for things we aren't interested in, including files rooted in /suite, /db, etc. Since we are interested in finding this behaviour in Firefox, we need to focus on the files rooted in '''/browser'''. One looks particularly interesting:
<blockquote>httpCreate a file named://lxr'''addtabbeside@senecac.mozillaon.org/seamonkey/source/browser/base/content/browser.xul#503</blockquote>ca'''
In this case, the tabbrowser widget has the onnewtab property set to another function, '''BrowserOpenTab();''' (i.e., Firefox seems to handle tab creation in a non-standard way, providing its own method instead of using This file should contain the default). Since we want full path to find the definition of this functionyour extension, we search for '''"function BrowserOpenTab("''', which returns two resultsexample:
<blockquote>http C://lxr.mozilla.org/seamonkey/search?string=function+browseropentab%28</blockquote>\temp\addtabbeside
Again, weNow put this file in your development profile're interested in Firefox s extensions directory (i.e., browser) instead of SeaMonkey (i.e., suiteNOTE: replace ''Username'' with your username and ''dev-profile'' with your development profile name), so we skip to the second result:
<blockquote>http C://lxr.mozilla.org/seamonkey/source/browser/base/content/browser.js#1802</blockquote> This shows us that we need to be looking for yet another function, \Documents and Settings\''Username'loadOneTab()'\Application Data\Mozilla\Firefox\Profiles\''. Another search:dev-profile''\extensions
<blockquote>http://lxr.mozilla.org/seamonkey/search?string=loadonetab</blockquote>
The first result is not surprising, and we're back to the tabbrowser widget. The '''loadOneTab''' method calls another method to actually create and insert the new tab:
var tab = this.addTab(aURI, aReferrerURI, aCharset, aPostData, owner, aAllowThirdPartyFixup);
Since '''addTab''' is a method of '''this''' we can search within the current document (CTRL+F) to find the '''addTab''' method. Finally we've found the right spot!
<blockquote>http://lxr.mozilla.org/seamonkey/source/toolkit/content/widgets/tabbrowser.xml#1160</blockquote>
this.mTabContainer.appendChild(t);
Now all that we have to do is modify it to insert rather than append.
=The 'How': the necessary changes to the code=
There are different ways you could go about making this change, and someone with more experience using tabbrowser might recommend a different strategy or outcome. I decided to work on something that I knew nothing about in order to highlight the process one goes through, or at least the process I went through, when working with someone else's code. Since my goal is to show you how to do this, I also discuss my errors and mistakes below--they are an important part of the process too.
==First Attempt==
The goal is to make as small a change as possible, since the existing code works well--I just want it to work slightly different. I'm also not interested in reading all of the code in order to make such a small change. I want to leverage as much of what is already there as I can.
I assume that the '''appendChild()''' method is responsible for the behaviour I don't like (i.e., adding new tabs to the end of the list). I'm not sure what to replace it with, so I do another search inside tabbrowser.xml (i.e., using CTRL+F) looking for other methods/attributes of '''mTabContainer'''. I come-up with some interesting options:
index = this.mTabContainer.selectedIndex;
...
this.mTabContainer.insertBefore(aTab, this.mTabContainer.childNodes.item(aIndex));
...
var position = this.mTabContainer.childNodes.length-1;
I decide that I can probably accomplish my goal using these alone, and so start working on a solution. Here is my first attempt, showing the changes to '''mozilla/toolkit/content/widgets/tabbrowser.xml''' and the '''addTab''' method:
// Insert tab after current tab, not at end. if (this.mTabContainer.childNodes.length == 0) { this.mTabContainer.appendChild(t); } else { var currentTabIndex First Attempt== this.mTabContainer.selectedIndex; this.mTabContainer.insertBefore(t, currentTabIndex + 1); } I then repackage the toolkit.jar file (change ''objdir'' to your objdir name):   $ cd mozilla/''objdir''/toolkit/content $ make then run the browser to test (NOTE: ''minefield'' is my testing profile):  $ ../../dist/bin/firefox.exe -p minefield --no-remote I try to create a new tab using '''File > New Tab''' and nothing happens.
==Second Attempt==
 
Clearly my code has some problems, since I've completely broken addTab. I decide to look for clues in the '''Error Console''' (Tools > Error Console) and notice the following exception whenever I try to add a new tab:
 
<code>Error: uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: chrome://global/content/bindings/tabbrowser.xml :: addTab :: line 1161" data: no]</code>
 
I make a guess that childNodes.length is not zero, but 1 by default (i.e., there is always at least one tab, even if it isn't visible). A quick modification to the code, and I test again:
 
if (this.mTabContainer.childNodes.length '''== 1''') {
...
==Third Attempt==
This works, but only the first time I create a new tab. Clearly I still have some misconceptions about how '''mTabContainer.selectedIndex''' and '''mTabContainer.insertBefore()''' really work.
 
I can't yet see how my code is wrong, but the exception I'm getting clearly indicates that I've got some sort of type conversion problem. I decide to look again at the code examples in tabbrowser.xml that I'm using as a guide, specifically '''insertChild()'''.
 
After a few seconds the error is obvious: I've used an Integer where a Tab was required. Here is the corrected code:
 
// Insert tab after current tab, not at end.
if (this.mTabContainer.childNodes.length == 1) {
this.mTabContainer.appendChild(t);
} else {
var currentTabIndex = this.mTabContainer.selectedIndex;
this.mTabContainer.insertBefore(t, '''this.mTabContainer.childNodes.item(currentTabIndex + 1)''');
}
==Success, and some bugs==
After repackaging the toolkit.jar file and running the browser, I'm able to confirm that this last change has been successful. Opening a new tab now works in the way I originally described. I make a few more tests to insure that I haven't broken anything else, for example, what happens if I am on the last tab and not in the middle. This works, which makes me realize that using '''append()''' is probably not necessary at all, and I can safely shorten my code down to the following:
 
// Insert tab after current tab, not at end.
var currentTabIndex = this.mTabContainer.selectedIndex;
this.mTabContainer.insertBefore(t, this.mTabContainer.childNodes.item(currentTabIndex + 1));
 
This means that six lines of code become two, and with that reduction in number of lines, hopefully a reduction in new bugs I've added (NOTE: within reason, favour fewer rather than more lines of code).
 
Speaking of bugs, a closer read of '''addTab''' (see [http://lxr.mozilla.org/seamonkey/source/toolkit/content/widgets/tabbrowser.xml#1219 line 1219]) would indicate that we've introduced a few with our new positioning code:
 
// wire up a progress listener for the new browser object.
var position = '''this.mTabContainer.childNodes.length-1;'''
var tabListener = this.mTabProgressListener(t, b, blank);
...
this.mTabListeners[position] = tabListener;
this.mTabFilters[position] = filter;
...
t._tPos = position;
 
Where the assumption before was that the newly created tab was at the end of the list, the new code breaks that. Therefore, we also need to update the value of '''position'''
 
// wire up a progress listener for the new browser object.
var position = currentTabIndex + 1
No other obvious defects are visible from our changes.
=Reflections=
 
The change I was making was simple enough that I didn't bother looking at any documentation or using the JavaScript debugger. I found out afterward that tabbrowser has good [http://developer.mozilla.org/en/docs/XUL:tabbrowser documentation on MDC].
 
Another trick worth trying when you're making lots of JavaScript changes like this is to add the following line to your .mozconfig file:
 
ac_add_options --enable-chrome-format=flat
 
This will cause the .jar files to be expanded so that you can edit the .xml/.js/.xul files in place and skip the repackaging step above (see http://www.mozilla.org/build/jar-packaging.html). If you also use the [http://ted.mielczarek.org/code/mozilla/extensiondev/index.html Extension Developer's extension] you can reload the chrome without restarting the browser.
* [http://developer.mozilla.org/en/docs/Extensions Extensions on MDC]
* [http://kb.mozillazine.org/Extension_development Extension Development on Mozillazine]
* [http://developer.mozilla.org/en/docs/XUL_Event_Propagation XUL Event Propagation]

Navigation menu