aboutsummaryrefslogtreecommitdiff
path: root/files/de/codeschnipsel/tabbed_browser/index.html
blob: f08d80a7d4d1bd27fb3cbbc27e9c62a5c4b2c0e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
---
title: Tabbed browser
slug: Codeschnipsel/Tabbed_browser
translation_of: Archive/Add-ons/Tabbed_browser
---
<p>Here you should find a set of useful code snippets to help you work with Firefox's tabbed browser. The comments normally mark where you should be inserting your own code.</p>
<p>Each snippet normally includes some code to run at initialization, these are best run using a <a href="/en/Extension_Frequently_Asked_Questions#Why_doesn.27t_my_script_run_properly.3F" title="en/Extension_Frequently_Asked_Questions#Why_doesn.27t_my_script_run_properly.3F">load listener</a>. These snippets assume they are run in the context of a browser window. If you need to work with tabs from a non-browser window, you need to obtain a reference to one first, see <a href="/en/Working_with_windows_in_chrome_code" title="en/Working_with_windows_in_chrome_code">Working with windows in chrome code</a> for details.</p>
<h3 id="Getting_access_to_the_browser" name="Getting_access_to_the_browser">Multiple meanings for the word 'browser'</h3>
<p>The word 'browser' is used several ways. Of course the entire application Firefox is called "a browser". Within the Firefox browser are tabs and inside each tab is a browser, both in the common sense of a web page browser and the XUL sense of a {{ XULElem("browser") }} element. Furthermore another meaning of 'browser' in this document and in some Firefox source is "the <a href="/en-US/docs/XUL/tabbrowser" title="/en-US/docs/XUL/tabbrowser">tabbrowser</a> element" in a Firefox XUL window.</p>
<h3 id="Getting_access_to_the_browser" name="Getting_access_to_the_browser">Getting access to the browser</h3>
<h4 id="From_main_window">From main window</h4>
<p>Code running in Firefox's global ChromeWindow, common for extensions that overlay into <code>browser.xul</code>, can access the {{ XULElem("tabbrowser") }} element using the global variable <code>gBrowser.</code></p>
<pre class="eval">// gBrowser is only accessible from the scope of
// the browser window (browser.xul)
gBrowser.addTab(...);
</pre>
<p>If <code>gBrowser</code> isn't defined your code is either not running in the scope of the browser window or running too early. You can access <code>gBrowser</code> only after the browser window is fully loaded. If you need to do something with <code>gBrowser</code> right after the window is opened, <a href="/en/DOM/element.addEventListener" title="en/DOM/element.addEventListener">listen</a> for the <code>load</code> event and use <code>gBrowser</code> in the event listener.</p>
<p>If your code does not have access to the main window because it is run in a sidebar or dialog, you first need to get access to the browser window you need before you can use <code>gBrowser</code>. You can find more information on getting access to the browser window in <a href="/en/Working_with_windows_in_chrome_code" title="en/Working_with_windows_in_chrome_code">Working with windows in chrome code</a>.</p>
<h4 id="From_a_sidebar">From a sidebar</h4>
<p>Basically, if your extension code is a sidebar you can use:</p>
<pre class="brush: js">var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                       .getInterface(Components.interfaces.nsIWebNavigation)
                       .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                       .rootTreeItem
                       .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                       .getInterface(Components.interfaces.nsIDOMWindow);

mainWindow.gBrowser.addTab(...);
</pre>
<h4 id="From_a_dialog">From a dialog</h4>
<p>If your code is running in a dialog opened directly by a browser window, you can use:</p>
<pre class="eval">window.opener.gBrowser.addTab(...);
</pre>
<p>If <code>window.opener</code> doesn't work, you can get the most recent browser window using this code:</p>
<pre class="brush: js">var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var mainWindow = wm.getMostRecentWindow("navigator:browser");
mainWindow.gBrowser.addTab(...);
</pre>
<h3 id="Opening_a_URL_in_a_new_tab" name="Opening_a_URL_in_a_new_tab">Opening a URL in a new tab</h3>
<pre class="brush: js">// Add tab
gBrowser.addTab("http://www.google.com/");

// Add tab, then make active
gBrowser.selectedTab = gBrowser.addTab("http://www.google.com/");
</pre>
<h4 id="Manipulating_content_of_a_new_tab" name="Manipulating_content_of_a_new_tab">Manipulating content of a new tab</h4>
<p>If you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading.</p>
<pre class="brush: js">// WRONG WAY (the page hasn't finished loading yet)
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/"));
alert(newTabBrowser.contentDocument.body.innerHTML);

// BETTER WAY
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/"));
newTabBrowser.addEventListener("load", function () {
  newTabBrowser.contentDocument.body.innerHTML = "&lt;div&gt;hello world&lt;/div&gt;";
}, true);
</pre>
<p>(The event target in the onLoad handler will be a 'tab' XUL element). See <a href="/en/XUL/tabbrowser#m-getBrowserForTab" title="en/XUL/tabbrowser#m-getBrowserForTab">tabbrowser</a> for getBrowserForTab(). N<span style="line-height: 1.5;">ote that the code above does not work inside of the Electrolysis (e10s)</span><span style="line-height: 1.5;"> enabled tabs.</span></p>
<h4 id="Opening_a_URL_in_the_correct_window.2Ftab" name="Opening_a_URL_in_the_correct_window.2Ftab">Opening a URL in the correct window/tab</h4>
<p>There are methods available in <code><a class="external" href="http://mxr.mozilla.org/mozilla-central/source/browser/base/content/utilityOverlay.js" rel="external nofollow" title="http://mxr.mozilla.org/mozilla-central/source/browser/base/content/utilityOverlay.js">chrome://browser/content/utilityOverlay.js</a></code> that make it easy to open URL in tabs such as <code>openUILinkIn</code> and <code>openUILink</code>.</p>
<dl>
 <dt>
  <code>openUILinkIn( url, where, allowThirdPartyFixup, postData, referrerUrl ) </code></dt>
 <dd>
  where:
  <ul>
   <li>"current" current tab (if there aren't any browser windows, then in a new window instead)</li>
   <li>"tab" new tab (if there aren't any browser windows, then in a new window instead)</li>
   <li>"tabshifted" same as "tab" but in background if default is to select new tabs, and vice versa</li>
   <li>"window" new window</li>
   <li>"save" save to disk (with no filename hint!)</li>
  </ul>
 </dd>
 <dt>
  <code>openUILink( url, e, ignoreButton, ignoreAlt, allowKeywordFixup, postData, referrerUrl ) </code></dt>
 <dd>
   </dd>
</dl>
<p>The following code will open a URL in a new tab, an existing tab, or an existing window based on which mouse button was pressed and which hotkeys (ex: Ctrl) are being held. The code given is for a {{ XULElem("menuitem") }}, but will work equally well for other XUL elements. This will only work in an overlay of browser.xul.</p>
<p>XUL:</p>
<pre class="eval">&lt;menuitem oncommand="myExtension.foo(event)" onclick="checkForMiddleClick(this, event)" label="Click me"/&gt;
</pre>
<p>JS:</p>
<pre class="brush: js">var myExtension = {
  foo: function(event) {
    openUILink("http://www.example.com", event, false, true);
  }
}</pre>
<h4 id="Opening_a_URL_in_an_on_demand_tab">Opening a URL in an on demand tab</h4>
<pre class="brush: js">var gSessionStore = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);

// Create new tab, but don't load the content.
var url = "https://developer.mozilla.org";
var tab = gBrowser.addTab(null);
gSessionStore.setTabState(tab, JSON.stringify({
  entries: [
    { url: url, title: url }
  ],
  lastAccessed: 0,
  index: 1,
  hidden: false,
  attributes: {},
  image: null
}));
</pre>
<h4 id="Reusing_tabs" name="Reusing_tabs">Reusing tabs</h4>
<p>Rather than open a new browser or new tab each and every time one is needed, it is good practice to try to re-use an existing tab which already displays the desired URL--if one is already open. Following this practice minimizes the proliferation of tabs and browsers created by your extension.</p>
<h5 id="Reusing_by_URL.2FURI" name="Reusing_by_URL.2FURI">Reusing by URL/URI</h5>
<p>A common feature found in many extensions is to point the user to <code>chrome://</code> URIs in a browser window (for example, help or about information) or external (on-line <code>http(s)://</code>) HTML documents when the user clicks an extension's button or link. The following code demonstrates how to re-use an existing tab that already displays the desired URL/URI. If no such tab exists, a new one is opened with the specified URL/URI.</p>
<pre class="brush: js">function openAndReuseOneTabPerURL(url) {
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);
  var browserEnumerator = wm.getEnumerator("navigator:browser");

  // Check each browser instance for our URL
  var found = false;
  while (!found &amp;&amp; browserEnumerator.hasMoreElements()) {
    var browserWin = browserEnumerator.getNext();
    var tabbrowser = browserWin.gBrowser;

    // Check each tab of this browser instance
    var numTabs = tabbrowser.browsers.length;
    for (var index = 0; index &lt; numTabs; index++) {
      var currentBrowser = tabbrowser.getBrowserAtIndex(index);
      if (url == currentBrowser.currentURI.spec) {

        // The URL is already opened. Select this tab.
        tabbrowser.selectedTab = tabbrowser.tabContainer.childNodes[index];

        // Focus *this* browser-window
        browserWin.focus();

        found = true;
        break;
      }
    }
  }

  // Our URL isn't open. Open it now.
  if (!found) {
    var recentWindow = wm.getMostRecentWindow("navigator:browser");
    if (recentWindow) {
      // Use an existing browser window
      recentWindow.delayedOpenTab(url, null, null, null, null);
    }
    else {
      // No browser windows are open, so open a new one.
      window.open(url);
    }
  }
}
</pre>
<h5 id="Reusing_by_other_criteria" name="Reusing_by_other_criteria">Reusing by other criteria</h5>
<p>Sometimes you want to reuse a previously-opened tab regardless of which URL/URI it displays. This assumes the tab is opened by your extension, not by some other browser component. We can do re-use an arbitrary tab by attaching a custom attribute to it when we first open it. Later, when we want to re-use that tab, we iterate over all open tabs looking for one which has our custom attribute. If such a tab exists, we change its URL/URI and focus/select it. If no such tab exists (perhaps the user closed it or we never opened it in the first place), we create a new tab with our custom attribute.</p>
<pre class="brush: js">function openAndReuseOneTabPerAttribute(attrName, url) {
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);
  for (var found = false, index = 0, tabbrowser = wm.getEnumerator('navigator:browser').getNext().gBrowser;
       index &lt; tabbrowser.tabContainer.childNodes.length &amp;&amp; !found;
       index++) {

    // Get the next tab
    var currentTab = tabbrowser.tabContainer.childNodes[index];

    // Does this tab contain our custom attribute?
    if (currentTab.hasAttribute(attrName)) {

      // Yes--select and focus it.
      tabbrowser.selectedTab = currentTab;

      // Focus *this* browser window in case another one is currently focused
      tabbrowser.ownerDocument.defaultView.focus();
      found = true;
    }
  }

  if (!found) {
    // Our tab isn't open. Open it now.
    var browserEnumerator = wm.getEnumerator("navigator:browser");
    var tabbrowser = browserEnumerator.getNext().gBrowser;

    // Create tab
    var newTab = tabbrowser.addTab(url);
    newTab.setAttribute(attrName, "xyz");

    // Focus tab
    tabbrowser.selectedTab = newTab;

    // Focus *this* browser window in case another one is currently focused
    tabbrowser.ownerDocument.defaultView.focus();
  }
}
</pre>
<p>The function can be called like so:</p>
<pre class="eval"><span class="nowiki">openAndReuseOneTabPerAttribute("myextension-myattribute", "http://developer.mozilla.org/")</span>.
</pre>
<h3 id="Closing_a_tab" name="Closing_a_tab">Closing a tab</h3>
<p>This example closes the currently selected tab.</p>
<pre class="eval">gBrowser.removeCurrentTab();
</pre>
<p>There is also a more generic <code>removeTab</code> method, which accepts a XUL {{ XULElem("tab") }} element as its single parameter.</p>
<h3 id="Changing_active_tab" name="Changing_active_tab">Changing active tab</h3>
<p>This moves one tab forward (to the right).</p>
<pre>gBrowser.tabContainer.advanceSelectedTab(1, true);
</pre>
<p>This moves one tab to the left.</p>
<pre>gBrowser.tabContainer.advanceSelectedTab(-1, true);
</pre>
<h3 id="Detecting_page_load" name="Detecting_page_load">Detecting page load</h3>
<p>See also <a href="/en/Code_snippets/On_page_load" title="en/Code_snippets/On_page_load">Code snippets:On page load</a></p>
<pre class="brush: js">function examplePageLoad(event) {
  if (event.originalTarget instanceof Components.interfaces.nsIDOMHTMLDocument) {
    var win = event.originalTarget.defaultView;
    if (win.frameElement) {
      // Frame within a tab was loaded. win should be the top window of
      // the frameset. If you don't want do anything when frames/iframes
      // are loaded in this web page, uncomment the following line:
      // return;
      // Find the root document:
      win = win.top;
    }
  }
}

// do not try to add a callback until the browser window has
// been initialised. We add a callback to the tabbed browser
// when the browser's window gets loaded.
window.addEventListener("load", function () {
  // Add a callback to be run every time a document loads.
  // note that this includes frames/iframes within the document
  gBrowser.addEventListener("load", examplePageLoad, true);
}, false);

...
// When no longer needed
gBrowser.removeEventListener("load", examplePageLoad, true);
...
</pre>
<h3 id="Notification_when_a_tab_is_added_or_removed" name="Notification_when_a_tab_is_added_or_removed">Notification when a tab is added or removed</h3>
<pre class="brush: js">function exampleTabAdded(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been added
}

function exampleTabMoved(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been moved
}

function exampleTabRemoved(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been removed
}

// During initialization
var container = gBrowser.tabContainer;
container.addEventListener("TabOpen", exampleTabAdded, false);
container.addEventListener("TabMove", exampleTabMoved, false);
container.addEventListener("TabClose", exampleTabRemoved, false);

// When no longer needed
container.removeEventListener("TabOpen", exampleTabAdded, false);
container.removeEventListener("TabMove", exampleTabMoved, false);
container.removeEventListener("TabClose", exampleTabRemoved, false);
</pre>
<div class="note">
 <p><strong>Note:</strong> Starting in {{Gecko("1.9.1") }}, there's an easy way to <a href="/En/Listening_to_events_on_all_tabs" title="https://developer.mozilla.org/en/Listening_to_events_on_all_tabs">listen on progress events on all tabs</a>.</p>
</div>
<p>{{ h2_gecko_minversion("Notification when a tab's attributes change", "2.0") }}</p>
<p>Starting in Gecko 2.0, you can detect when a tab's attributes change by listening for the <code>TabAttrModified</code> event. The attributes to which changes result in this event being sent are:</p>
<ul>
 <li>{{ xulattr("label") }}</li>
 <li>{{ xulattr("crop") }}</li>
 <li>{{ xulattr("busy") }}</li>
 <li>{{ xulattr("image") }}</li>
 <li>{{ xulattr("selected") }}</li>
</ul>
<pre class="brush: js">function exampleTabAttrModified(event) {
  var tab = event.target;
  // Now you can check what's changed on the tab
}

// During initialization
var container = gBrowser.tabContainer;
container.addEventListener("TabAttrModified", exampleTabAttrModified, false);

// When no longer needed
container.removeEventListener("TabAttrModified", exampleTabAttrModified, false);
</pre>
<p>{{ h2_gecko_minversion("Notification when a tab is pinned or unpinned", "2.0") }}</p>
<p>Starting in Gecko 2.0, tabs can be "pinned"; that is, they become special application tabs ("app tabs"), which are pinned to the beginning of the tab bar, and show only the favicon. You can detect when a tab becomes pinned or unpinned by watching for the <code>TabPinned</code> and <code>TabUnpinned</code> events.</p>
<pre class="brush: js">function exampleTabPinned(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been pinned
}

function exampleTabUnpinned(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been pinned
}

// Initialization

var container = gBrowser.tabContainer;
container.addEventListener("TabPinned", exampleTabPinned, false);
container.addEventListener("TabUnpinned", exampleTabUnpinned, false);

// When no longer needed

container.removeEventListener("TabPinned", exampleTabPinned, false);
container.removeEventListener("TabUnpinned", exampleTabUnpinned, false);
</pre>
<h3 id="Detecting_tab_selection" name="Detecting_tab_selection">Detecting tab selection</h3>
<p>The following code allows you to detect when a new tab is selected in the browser:</p>
<pre class="brush: js">function exampleTabSelected(event) {
  var browser = gBrowser.selectedBrowser;
  // browser is the XUL element of the browser that's just been selected
}

// During initialisation
var container = gBrowser.tabContainer;
container.addEventListener("TabSelect", exampleTabSelected, false);

// When no longer needed
container.removeEventListener("TabSelect", exampleTabSelected, false);
</pre>
<h3 id="Getting_document_of_currently_selected_tab" name="Getting_document_of_currently_selected_tab">Getting document of currently selected tab</h3>
<p>The following code allows you to retrieve the document that is in the selected tab. This code will work in the scope of the browser window (e.g. you're working from an overlay to the browser window).</p>
<pre class="eval">gBrowser.contentDocument;
</pre>
<p>or</p>
<pre class="eval">content.document
</pre>
<p>If you're working from a window or dialog that was opened by the browser window, you can use this code to get the document displayed in the selected tab in the browser window that opened the new window or dialog.</p>
<pre class="eval">window.opener.content.document
</pre>
<p>From windows or dialogs not opened by the browser window, you can use {{ interface("nsIWindowMediator") }} to get the document displayed in the selected tab of the most recently used browser window.</p>
<pre class="brush: js">var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var recentWindow = wm.getMostRecentWindow("navigator:browser");
return recentWindow ? recentWindow.content.document.location : null;
</pre>
<p>See also <a href="/en/Working_with_windows_in_chrome_code#Content_windows" title="en/Working_with_windows_in_chrome_code#Content_windows">Working with windows in chrome code</a>.</p>
<h3 id="Enumerating_tabs" name="Enumerating_tabs">Enumerating browsers</h3>
<p>To go through all browser in a tabbrowser, first get a reference to a browser's window. If your code is executed from a Firefox <code>browser.xul</code> overlay (for example, it is a toolbar button or menu <em>click</em> handler), you can access the current window with the <code>window</code> pre-defined variable. However, if your code is executed from its own window (for example, a settings/options dialog), you can use {{ interface("nsIWindowMediator") }} to get a browser's window.</p>
<p>Next, get the <code>&lt;tabbrowser/&gt;</code> element. You can get it with <code>win.gBrowser</code>, where <code>win</code> is the browser's window from the previous step. You can use simply <code>gBrowser</code> instead of <code>window.gBrowser</code> if running in the context of a <code>browser.xul</code> overlay.</p>
<p>Finally, use <code>gBrowser.browsers.length</code> to get the number of browsers and <code>gBrowser.getBrowserAtIndex()</code> to get a <code>&lt;browser/&gt;</code> element. For example:</p>
<pre class="brush: js">var num = gBrowser.browsers.length;
for (var i = 0; i &lt; num; i++) {
  var b = gBrowser.getBrowserAtIndex(i);
  try {
    dump(b.currentURI.spec); // dump URLs of all open tabs to console
  } catch(e) {
    Components.utils.reportError(e);
  }
}</pre>
<p>To learn what methods are available for <code>&lt;browser/&gt;</code> and <code>&lt;tabbrowser/&gt;</code> elements, use <a href="/en/DOM_Inspector" title="en/DOM_Inspector">DOM Inspector</a> or look in {{ source("toolkit/content/widgets/browser.xml","browser.xml") }} for corresponding XBL bindings (or just look at the current reference pages on {{ XULElem("browser") }} and {{ XULElem("tabbrowser") }}.</p>
<h3 id="Getting_the_browser_that_fires_the_http-on-modify-request_notification">Getting the browser that fires the http-on-modify-request notification</h3>
<p>See the <a href="/en/Observer_Notifications#HTTP_requests" title="en/Observer_Notifications#HTTP_requests">Observer notifications</a> page for information on http-on-* notifications.</p>
<p>Note that some HTTP requests aren't associated with a tab; for example, RSS feed updates, extension manager requests, XHR requests from XPCOM components, etc. In those cases, the following code returns null.</p>
<div class="warning">
 <strong>Warning:</strong> This code should be updated to use {{interface("nsILoadContext")}} instead of <code>getInterface(Components.interfaces.nsIDOMWindow)</code>, <a href="/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request" title="/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request">see this example</a>..<a href="#Getting_the_browser_that_fires_the_http-on-modify-request_notification_(example_code_updated_for_loadContext)">UPDATED EXAMPLE IS IN SECTION BELOW THIS</a></div>
<pre class="brush: js">observe: function (subject, topic, data) {
  if (topic == "http-on-modify-request") {
    subject.QueryInterface(Components.interfaces.nsIHttpChannel);
    var url = subject.URI.spec; /* url being requested. you might want this for something else */
    var browser = this.getBrowserFromChannel(subject);
    if (browser != null) {
      /* do something */
    }
  }
},

getBrowserFromChannel: function (aChannel) {
  try {
    var notificationCallbacks =
      aChannel.notificationCallbacks ? aChannel.notificationCallbacks : aChannel.loadGroup.notificationCallbacks;

    if (!notificationCallbacks)
      return null;

    var domWin = notificationCallbacks.getInterface(Components.interfaces.nsIDOMWindow);
    return gBrowser.getBrowserForDocument(domWin.top.document);
  }
  catch (e) {
    dump(e + "\n");
    return null;
  }
}
</pre>
<h3 id="Getting_the_browser_that_fires_the_http-on-modify-request_notification_(example_code_updated_for_loadContext)">Getting the browser that fires the http-on-modify-request notification (example code updated for loadContext)</h3>
<p>Here an example of the previous section is shown. The previous section was left intact so people can see the old way of doing things.</p>
<pre class="brush: js">Components.utils.import('resource://gre/modules/Services.jsm');
Services.obs.addObserver(httpObs, 'http-on-modify-request', false);
//Services.obs.removeObserver(httpObs, 'http-on-modify-request'); //uncomment this line, or run this line when you want to remove the observer

var httpObs = {
    observe: function (aSubject, aTopic, aData) {
        if (aTopic == 'http-on-modify-request') {
            /*start - do not edit here*/
            var oHttp = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel); //i used nsIHttpChannel but i guess you can use nsIChannel, im not sure why though
            var interfaceRequestor = oHttp.notificationCallbacks.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
            //var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request //instead do the loadContext stuff below
            var loadContext;
            try {
                loadContext = interfaceRequestor.getInterface(Components.interfaces.nsILoadContext);
            } catch (ex) {
                try {
                    loadContext = aSubject.loadGroup.notificationCallbacks.getInterface(Components.interfaces.nsILoadContext);
                    //in ff26 aSubject.loadGroup.notificationCallbacks was null for me, i couldnt find a situation where it wasnt null, but whenever this was null, and i knew a loadContext is supposed to be there, i found that "interfaceRequestor.getInterface(Components.interfaces.nsILoadContext);" worked fine, so im thinking in ff26 it doesnt use aSubject.loadGroup.notificationCallbacks anymore, but im not sure
                } catch (ex2) {
                    loadContext = null;
                    //this is a problem i dont know why it would get here
                }
            }
            /*end do not edit here*/
            /*start - do all your edits below here*/
            var url = oHttp.URI.spec; //can get url without needing loadContext
            if (loadContext) {
                var contentWindow = loadContext.associatedWindow; //this is the HTML window of the page that just loaded
                //aDOMWindow this is the firefox window holding the tab
                var aDOMWindow = contentWindow.top.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShellTreeItem).rootTreeItem.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow);
                var gBrowser = aDOMWindow.gBrowser; //this is the gBrowser object of the firefox window this tab is in
                var aTab = gBrowser._getTabForContentWindow(contentWindow.top); //this is the clickable tab xul element, the one found in the tab strip of the firefox window, aTab.linkedBrowser is same as browser var above //can stylize tab like aTab.style.backgroundColor = 'blue'; //can stylize the tab like aTab.style.fontColor = 'red';
                var browser = aTab.linkedBrowser; //this is the browser within the tab //this is what the example in the previous section gives
                //end getting other useful stuff
            } else {
                Components.utils.reportError('EXCEPTION: Load Context Not Found!!');
                //this is likely no big deal as the channel proably has no associated window, ie: the channel was loading some resource. but if its an ajax call you may end up here
            }
        }
    }
};
</pre>
<p>Here's a cleaner example of the same thing:</p>
<pre><code>Cu.import('resource://gre/modules/Services.jsm');

var httpRequestObserver = {
    observe: function (subject, topic, data) {
        var httpChannel, requestURL;

        if (topic == "http-on-modify-request") {
            httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
            requestURL = httpChannel.URI.spec;

            var newRequestURL, i;

            if (/someurl/.test(requestURL)) {
                var goodies = loadContextGoodies(httpChannel);
                if (goodies) {
                    httpChannel.cancel(Cr.NS_BINDING_ABORTED);
                    goodies.contentWindow.location = self.data.url('pages/test.html');
                } else {
                    //dont do anything as there is no contentWindow associated with the httpChannel, liekly a google ad is loading or some ajax call or something, so this is not an error
                }
            }

            return;
        }
    }
};
Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false);





//this function gets the contentWindow and other good stuff from loadContext of httpChannel
function loadContextGoodies(httpChannel) {
    //httpChannel must be the subject of http-on-modify-request QI'ed to nsiHTTPChannel as is done on line 8 "httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);"
    //start loadContext stuff
    var loadContext;
    try {
        var interfaceRequestor = httpChannel.notificationCallbacks.QueryInterface(Ci.nsIInterfaceRequestor);
        //var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request //instead do the loadContext stuff below
        try {
            loadContext = interfaceRequestor.getInterface(Ci.nsILoadContext);
        } catch (ex) {
            try {
                loadContext = subject.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);
            } catch (ex2) {}
        }
    } catch (ex0) {}

    if (!loadContext) {
        //no load context so dont do anything although you can run this, which is your old code
        //this probably means that its loading an ajax call or like a google ad thing
        return null;
    } else {
        var contentWindow = loadContext.associatedWindow;
        if (!contentWindow) {
            //this channel does not have a window, its probably loading a resource
            //this probably means that its loading an ajax call or like a google ad thing
            return null;
        } else {
            var aDOMWindow = contentWindow.top.QueryInterface(Ci.nsIInterfaceRequestor)
                .getInterface(Ci.nsIWebNavigation)
                .QueryInterface(Ci.nsIDocShellTreeItem)
                .rootTreeItem
                .QueryInterface(Ci.nsIInterfaceRequestor)
                .getInterface(Ci.nsIDOMWindow);
            var gBrowser = aDOMWindow.gBrowser;
            var aTab = gBrowser._getTabForContentWindow(contentWindow.top); //this is the clickable tab xul element, the one found in the tab strip of the firefox window, aTab.linkedBrowser is same as browser var above //can stylize tab like aTab.style.backgroundColor = 'blue'; //can stylize the tab like aTab.style.fontColor = 'red';
            var browser = aTab.linkedBrowser; //this is the browser within the tab //this is where the example in the previous section ends
            return {
                aDOMWindow: aDOMWindow,
                gBrowser: gBrowser,
                aTab: aTab,
                browser: browser,
                contentWindow: contentWindow
            };
        }
    }
    //end loadContext stuff
}</code></pre>
<p>{{ languages( { "fr": "fr/Extraits_de_code/Onglets_de_navigation", "ja": "ja/Code_snippets/Tabbed_browser", "pl": "pl/Fragmenty_kodu/Przegl\u0105danie_w_kartach" } ) }}</p>