aboutsummaryrefslogtreecommitdiff
path: root/files/pt-pt/mozilla/trabalhar_com_janelas_no_codigo_chrome/index.html
blob: a3f012eb7a7e32a5185bacf386e5626fdc3b7123 (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
---
title: Trabalhar com janelas no código chrome
slug: Mozilla/trabalhar_com_janelas_no_codigo_chrome
tags:
  - Add-ons
  - Extensões
  - Extras
  - Guía
translation_of: Mozilla/Working_with_windows_in_chrome_code
---
<p>Este artigo descreve o trabalho com várias janelas no código da Mozilla (aplicações <a href="/en-US/docs/XUL" title="XUL">XUL</a> e <a href="/en-US/docs/Extensions" title="Extensions">Extensões</a>). Este contém dicas e código exemplo em como abrir novas janelas, encontrar uma janela já aberta, e passar dados entre diferentes janelas.</p>

<h2 id="Opening_windows" name="Opening_windows">Abertura de janelas</h2>

<h3 id="From_a_&lt;script>_in_a_window_or_an_overlay">From a &lt;script&gt; in a window or an overlay</h3>

<p>To open a new window, we usually use a <code><a href="/en-US/docs/DOM/window.open" title="DOM/window.open">window.open</a></code> or <code><a href="/en-US/docs/DOM/window.openDialog" title="DOM/window.openDialog">window.openDialog</a></code> DOM call, like this:</p>

<div style="overflow: hidden;">
<pre class="brush:js;auto-links:false;">var win = window.open("chrome://myextension/content/about.xul",
                      "aboutMyExtension", "chrome,centerscreen");
</pre>
</div>

<p>The first parameter to <code>window.open</code> is the URI of the XUL file that describes the window and its contents.</p>

<p>The second parameter is the window's name; the name can be used in links or forms as the <code>target</code> attribute. This is different from the user-visible window title, which is specified using XUL.</p>

<p>The third, and optional, parameter is a list of special window features the window should have.</p>

<p>The <code>window.openDialog</code> function works similarly, but lets you specify optional arguments that can be referenced from the JavaScript code. It also handles window features a little differently, including always assuming the <code>dialog</code> feature is specified.</p>

<h3 id="From_XPCOM_components_and_modules">From XPCOM components and modules</h3>

<p>If the <code>Window</code> object is unavailable (for example, when opening a window from XPCOM component code), you might want to use <a href="/en-US/docs/XPCOM_Interface_Reference/nsIWindowWatcher" title="nsIWindowWatcher">nsIWindowWatcher</a> interface. Its parameters are similar to <code>window.open</code>; in fact, <code>window.open</code>'s implementation calls <code>nsIWindowWatcher</code>'s methods.</p>

<div style="overflow: hidden;">
<pre class="brush:js;auto-links:false;">var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
                   .getService(Components.interfaces.nsIWindowWatcher);
var win = ww.openWindow(null, "chrome://myextension/content/about.xul",
                        "aboutMyExtension", "chrome,centerscreen", null);</pre>
</div>

<h2 id="Window_object" name="Window_object">Objeto de janela</h2>

<p>Note the <code>win</code> variable in the above section, which is assigned the return value of <code>window.open</code>. It can be used to access the opened window. The return value of <code>window.open</code> (and similar methods) is a <code>Window</code> object (usually <code>ChromeWindow</code>) – the same type as the <code>window</code> variable.</p>

<p>Technically speaking, it implements a number of interfaces, including {{ interface("nsIDOMJSWindow") }} and {{ interface("nsIDOMWindow") }}, but it also contains the user-defined properties for global variables and functions of the window. So, for example, to access the DOM document corresponding to the window, you can use <code><a href="/en-US/docs/DOM/window.document" title="DOM/window.document">win.document</a></code>.</p>

<p>Note however, that the <code>open()</code> call returns <em>before</em> the window is fully loaded, so some calls, like <code><a href="/en-US/docs/DOM/document.getElementById" title="DOM/document.getElementById">win.document.getElementById()</a></code> will fail. To overcome this difficulty, you can move the initialization code to a <code>load</code> handler of the window being opened or pass a callback function, as described <a href="#callback">below</a>.</p>

<p>You can get a <code>Window</code> object from a document using <code><a href="/en-US/docs/DOM/document.defaultView" title="DOM/document.defaultView">document.defaultView</a></code>.</p>

<h2 id="Content_windows" name="Content_windows">Janelas de conteúdo</h2>

<p>When a XUL window contains a widget capable of displaying a page, such as <code>&lt;browser&gt;</code> or <code>&lt;iframe&gt;</code>, the document in that widget is, naturally, separate from the document of the chrome window itself. There also is a <code>Window</code> object for each sub-document, although there's no window in a common sense for the sub-document.</p>

<p>The same holds for chrome windows opened inside a tab of <code>&lt;tabbrowser&gt;</code>. The elements above the chrome document opened in the tab are separate from your chrome document.</p>

<p>The following two subsections describe how to cross chrome-content boundaries in either way, i.e. accessing elements which are ancestors of your chrome document, or accessing elements which are descendants of your chrome document (but nevertheless in a different context).</p>

<h3 id="Accessing_content_documents" name="Accessing_content_documents">Accessing content documents</h3>

<p>Assume you have a document loaded in a <code>&lt;tabbrowser&gt;</code>, <code>&lt;browser&gt;</code>, or <code>&lt;iframe&gt;</code> element inside your document. You can use <code>browser.contentDocument</code> to access that document and <code>browser.contentWindow</code> to access the <code>Window</code> object of that document.</p>

<p>You should be aware of <a href="/en-US/docs/XPCNativeWrapper" title="XPCNativeWrapper">XPCNativeWrappers</a> when working with <a href="/en-US/docs/XPCNativeWrapper#What_is_a_trusted_window.3F" title="XPCNativeWrapper#What_is_a_trusted_window.3F">untrusted content</a>. With XPCNativeWrappers turned on (which is the default in Firefox 1.5+), your extension can safely access the DOM of the content document, but not the content JavaScript. Bypassing XPCNativeWrapper to work with content JavaScript directly can lead to security problems.</p>

<p>See <a href="/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages" title="Code_snippets/Interaction_between_privileged_and_non-privileged_pages">Interaction between privileged and non-privileged pages</a> if you need to interact with the content page.</p>

<h4 id="The_content_shortcut" name="The_content_shortcut">The <code>content</code> shortcut</h4>

<p>In case of <code>&lt;browser type="content-primary" /&gt;</code>, you can use the <a href="/en-US/docs/DOM/window.content" title="DOM/window.content">content</a> shortcut property to accesss the <code>Window</code> object of the content document. For example:</p>

<pre class="brush:js">// alerts the title of the document displayed in the content-primary widget

alert(content.document.title);</pre>

<p>For example, you can use <code>content.document</code> in a <code>browser.xul</code> overlay to access the web page in the selected tab in a Firefox window.</p>

<div class="note">Some examples use <code>_content</code> instead of <code>content</code>. The former has been deprecated for a while, and you should use <code>content</code> in the new code.</div>

<h3 id="Accessing_a_document_in_the_sidebar" name="Accessing_a_document_in_the_sidebar">Accessing a document in the sidebar</h3>

<p>Firefox has a sidebar, which is implemented as a <code>&lt;browser&gt;</code> element with id="sidebar". To access the elements and variables inside the sidebar, you need to use <code>document.getElementById("sidebar").contentDocument</code> or <code>.contentWindow</code>, like when {{ Anch("Accessing content documents") }}.</p>

<p>For more sidebar tips, see <a href="/en-US/docs/Code_snippets/Sidebar" title="Code_snippets/Sidebar">Code snippets:Sidebar</a>.</p>

<h3 id="Accessing_the_elements_of_the_top-level_document_from_a_child_window" name="Accessing_the_elements_of_the_top-level_document_from_a_child_window">Accessing the elements of the top-level document from a child window</h3>

<p>The opposite case is when you want to access the chrome document from a privileged script loaded in a <code>&lt;browser&gt;</code> or an <code>&lt;iframe&gt;</code>.</p>

<p>A typical case when this can be useful is when your code runs in the sidebar in the main Firefox window and you want to access the elements in the main browser window.</p>

<p>The DOM tree, as shown by the <a href="/en-US/docs/DOM_Inspector" title="DOM_Inspector">DOM Inspector</a>, can look like this:</p>

<pre>#document
  window                 main-window
    ...
      browser
        #document
          window         myExtensionWindow
</pre>

<p>where the child window is where your code runs in.</p>

<p>Your task is to access elements above your chrome document, i.e. to break out of your chrome window and access the ancestors. This can be done using the following statement:</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);</pre>

<p>This allows you to cross the chrome-content boundaries, and returns the main window object.</p>

<h2 id="Finding_already_opened_windows" name="Finding_already_opened_windows">Encontrar janelas já abertas</h2>

<p>The window mediator XPCOM component (<a href="/en-US/docs/XPCOM_Interface_Reference/nsIWindowMediator" title="nsIWindowMediator">nsIWindowMediator</a> interface) provides information about existing windows. Two of its methods are often used to obtain information about currently open windows: <code>getMostRecentWindow</code> and <code>getEnumerator</code>. Please refer to the <a href="/en-US/docs/XPCOM_Interface_Reference/nsIWindowMediator" title="nsIWindowMediator">nsIWindowMediator</a> page for more information and examples of using <code>nsIWindowMediator</code>. <span class="comment">=== Example: Opening a window only if it's not opened already === XXX TBD</span></p>

<h2 id="Passing_data_between_windows" name="Passing_data_between_windows">Passar dados entre janelas</h2>

<p>When working with multiple windows, you often need to pass information from one window to another. Since different windows have separate DOM documents and global objects for scripts, you can't just use one global JavaScript variable in scripts from different windows.</p>

<p>There are several techniques of varying power and simplicity that can be used to share data. We'll demonstrate them from the simplest to the most complex in the next few sections.</p>

<p>Note: if you want to pass data between privileged (chrome) and non-privileged (web page) windows, or vice-versa, <a href="/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages" title="Code snippets/Interaction between privileged and non-privileged pages">read this instead.</a></p>

<h3 id="Example_1:_Passing_data_to_window_when_opening_it_with_openDialog" name="Example_1:_Passing_data_to_window_when_opening_it_with_openDialog">Example 1: Passing data to window when opening it with <code>openDialog</code></h3>

<p>When you open a window using <code><a href="/en-US/docs/DOM/window.openDialog" title="DOM/window.openDialog">window.openDialog</a></code> or <code>nsIWindowWatcher.openWindow</code>, you can pass an arbitrary number of <em>arguments</em> to that window. Arguments are simple JavaScript objects, accessible through <code><a href="/en-US/docs/DOM/window.arguments" title="DOM/window.arguments">window.arguments</a></code> property in the opened window.</p>

<p>In this example, we're using <code>window.openDialog</code> to open a progress dialog. We pass in the current status text as well as the maximum and current progress values. Note that using <code>nsIWindowWatcher.openWindow</code> is a bit less trivial . <span class="comment">TODO: link to <a href="/en-US/docs/How_To_Pass_an_XPCOM_Object_to_a_New_Window" title="How_To_Pass_an_XPCOM_Object_to_a_New_Window">How To Pass an XPCOM Object to a New Window</a> when it has a more useful example</span></p>

<p>Opener code:</p>

<pre class="brush:js">window.openDialog("chrome://test/content/progress.xul",
                  "myProgress", "chrome,centerscreen",
                  {status: "Reading remote data", maxProgress: 50, progress: 10} );</pre>

<p><code>progress.xul</code>:</p>

<pre class="brush:xml">&lt;?xml version="1.0"?&gt;
&lt;?xml-stylesheet href="chrome://global/skin/" type="text/css"?&gt;

&lt;window onload="onLoad();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"&gt;
&lt;script&gt;&lt;![CDATA[

var gStatus, gProgressMeter;
var maxProgress = 100;

function onLoad() {
  gStatus = document.getElementById("status");
  gProgressMeter = document.getElementById("progressmeter");

  if("arguments" in window &amp;&amp; window.arguments.length &gt; 0) {
    maxProgress = window.arguments[0].maxProgress;
    setProgress(window.arguments[0].progress);
    setStatus(window.arguments[0].status);
  }
}

function setProgress(value) {
  gProgressMeter.value = 100 * value / maxProgress;
}

function setStatus(text) {
  gStatus.value = "Status: " + text + "...";
}

]]&gt;&lt;/script&gt;

&lt;label id="status" value="(No status)" /&gt;
&lt;hbox&gt;
  &lt;progressmeter id="progressmeter" mode="determined" /&gt;
  &lt;button label="Cancel" oncommand="close();" /&gt;
&lt;/hbox&gt;

&lt;/window&gt;</pre>

<h3 id="Example_2:_Interacting_with_the_opener" name="Example_2:_Interacting_with_the_opener">Example 2: Interacting with the opener</h3>

<p>Sometimes an opened window needs to interact with its opener; for example, it might do so in order to give notice that the user has made changes in the window. You can find the window's opener using its <a href="/en-US/docs/DOM/window.opener" title="DOM/window.opener">window.opener</a> property or via a callback function passed to the window in a way described in the previous section.</p>

<p>Let's add code to the previous example to notify the opener when the user presses Cancel on the progress dialog.</p>

<ul>
 <li><strong>Using <code>window.opener</code>.</strong> The <code>opener</code> property returns its window's opener; that is, the {{ Anch("Window object") }} that opened it.</li>
</ul>

<p>If we're sure the window that opened the progress dialog declares the <code>cancelOperation</code> function, we can use <code>window.opener.cancelOperation()</code> to notify it, like this:</p>

<pre class="brush:xml;">&lt;button label="Cancel" oncommand="opener.cancelOperation(); close();" /&gt;
</pre>

<ul>
 <li><strong>Using a callback function.</strong> Alternatively, the opener window can pass a callback function to the progress dialog in the same way we passed the status string in the previous example:</li>
</ul>

<pre class="brush:js">function onCancel() {
  alert("Operation canceled!");
}

...

window.openDialog(
  "chrome://test/content/progress.xul",
  "myProgress", "chrome,centerscreen",
  {status: "Reading remote data", maxProgress: 50, progress: 10},
  onCancel
);
</pre>

<p>The progress dialog can then run the callback like this:</p>

<pre class="brush:xml;">&lt;button label="Cancel" oncommand="window.arguments[1](); close();" /&gt;
</pre>

<h3 id="Example_3:_Using_nsIWindowMediator_when_opener_is_not_enough" name="Example_3:_Using_nsIWindowMediator_when_opener_is_not_enough">Example 3: Using <code>nsIWindowMediator</code> when <code>opener</code> is not enough</h3>

<p>The <code>window.opener</code> property is very easy to use, but it's only useful when you're sure that your window was opened from one of a few well-known places. In more complicated cases you need to use the <code><a href="/en-US/docs/XPCOM_Interface_Reference/nsIWindowMediator" title="nsIWindowMediator">nsIWindowMediator</a></code> interface, introduced above.</p>

<p>One case in which you might want to use <code>nsIWindowMediator</code> is in an extension's Options window. Suppose you're developing a browser extension that consists of a browser.xul overlay and an Options window. Suppose the overlay contains a button to open the extension's Options window which needs to read some data from the browser window. As you may remember, Firefox's Extension Manager can also be used to open your Options dialog.</p>

<p>This means the value of <code>window.opener</code> in your Options dialog is not necessarily the browser window -- instead, it might be the Extension Manager window. You could check the <code>location</code> property of the <code>opener</code> and use <code>opener.opener</code> in case it's the Extension Manager window, but a better way is to use <code>nsIWindowMediator</code>:</p>

<pre class="brush:js;">var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var browserWindow = wm.getMostRecentWindow("navigator:browser");
// read values from |browserWindow|</pre>

<p>You might be tempted to use a similar technique to apply the changes the user made in the Options dialog, but a better way to do that is to use <a href="/en-US/docs/Code_snippets/Preferences#Using_preference_observers" title="Code snippets/Preferences#Using preference observers">preferences observers</a>.</p>

<h3 id="Example_4_Using_nsIWindowWatcher_when_you_don't_have_a_window_(primitives_only)">Example 4: Using nsIWindowWatcher when you don't have a window (primitives only)</h3>

<p>For those times when you don't have access to a <code>window</code> object (such as a JavaScript XPCOM object), you can use <a href="/en-US/docs/XPCOM_Interface_Reference/nsIWindowWatcher#openWindow()" title="nsIWindowWatcher#openWindow()"><code>nsIWindowWatcher.openWindow</code></a> to open a XUL window. The problem is passing the data. It's a bit harder than using <code>window.openDialog</code>. Here is helper function that will package the data correctly and pass it to the newly opened window:</p>

<pre class="brush:js">function openDialog(parentWindow, url, windowName, features) {
    var array = Components.classes["@mozilla.org/array;1"]
                          .createInstance(Components.interfaces.nsIMutableArray);
    for (var i = 4; i &lt; arguments.length; i++) {
        var variant = Components.classes["@mozilla.org/variant;1"]
                                .createInstance(Components.interfaces.nsIWritableVariant);
        variant.setFromVariant(arguments[i]);
        array.appendElement(variant, false);
    }

    var watcher = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
                            .getService(Components.interfaces.nsIWindowWatcher);
    return watcher.openWindow(parentWindow, url, windowName, features, array);
}
</pre>

<p>The function almost works the same as <code>window.openDialog</code> but accepts an optional parent window as first parameter. The parent window can be null. The only data types that can be passed to the new window are primitives and arrays. JavaScript objects cannot be passed. All of the arguments are passed by value, that is to say that any changes made to the values in the new window will not affect the calling code.</p>

<h3 id="Example_5_Using_nsIWindowWatcher_for_passing_an_arbritrary_JavaScript_object">Example 5: Using nsIWindowWatcher for passing an arbritrary JavaScript object</h3>

<p>It is still possible to pass any JavaScript object using nsIWindowWatcher, it just takes a little more effort. In this example a single object is passed, though it is possible to pass multiple objects and primitives using a combination of this and the example above.</p>

<pre class="brush:js">// In the calling code
var args = {
  param1: true,
  param2: 42
};

args.wrappedJSObject = args;

var watcher = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
                            .getService(Components.interfaces.nsIWindowWatcher);

watcher.openWindow(null, url, windowName, features, args);</pre>

<pre class="brush:js">// In the window code
var args = window.arguments[0].wrappedJSObject;
</pre>

<p>This uses the <a href="/en-US/docs/wrappedJSObject" title="WrappedJSObject">wrappedJSObject</a> trick. By passing args to openWindow xpconnect will automatically wrap it as a generic nsISupports. The opened window can then just get at the underlying JavaScript object using wrappedJSObject.</p>

<h2 id="Advanced_data_sharing" name="Advanced_data_sharing">Partilha de dados avançada</h2>

<p>The above code is useful when you need to pass data from one window to another or to a set of windows, but sometimes you just want to share a JavaScript variable in common between different windows. You could declare a local variable in each window along with corresponding setter functions to keep the "instances" of the variable in sync across windows, but fortunately, there's a better way.</p>

<p>To declare a shared variable, we need to find a place that exists while the application is running and is easily accessible from the code in different chrome windows. There are actually a few such places.</p>

<h3 id="Using_JavaScript_code_modules" name="Using_JavaScript_code_modules">Using JavaScript code modules</h3>

<p><a href="/en-US/docs/JavaScript_code_modules/Using" title="Using_JavaScript_code_modules">JavaScript code modules</a> {{ Fx_minversion_inline(3) }} is a simple method for creating shared global singleton objects that can be imported into any other JavaScript scope. The importing scope will have access to the objects and data in the code module. Since the code module is cached, all scopes get the same instance of the code module and can share the data in the module. See <a href="/en-US/docs/Components.utils.import" title="Components.utils.import">Components.utils.import</a> for more information.</p>

<ul>
 <li>Pros:
  <ul>
   <li>It's the "right way"</li>
   <li>Very simple to make and import.</li>
   <li>No need to build an XPCOM component.</li>
  </ul>
 </li>
 <li>Cons:
  <ul>
   <li>Only works in Firefox 3 or newer.</li>
   <li>The scope is shared between modules and the importing scope, so you have to worry about name collisions.</li>
   <li>You can't use the <code><a href="/en-US/docs/DOM/window" title="DOM/window">window</a></code> object, its members, like <code>alert</code> and <code>open</code>, and many other objects available from inside a window. The functionality isn't lost, however -- you just have to use the XPCOM components directly instead of using convenient shortcuts. Of course, this doesn't matter if you just store data in the component.</li>
  </ul>
 </li>
</ul>

<h3 id="Using_an_XPCOM_singleton_component" name="Using_an_XPCOM_singleton_component">Using an XPCOM singleton component</h3>

<p>The cleanest and most powerful way to share data is to define your own XPCOM component (you can <a href="/en-US/docs/How_to_Build_an_XPCOM_Component_in_Javascript" title="How_to_Build_an_XPCOM_Component_in_Javascript">write one in JavaScript</a>) and access it from anywhere using a <code>getService</code> call:</p>

<pre class="brush:js">Components.classes["@domain.org/mycomponent;1"].getService();
</pre>

<ul>
 <li>Pros:
  <ul>
   <li>It's the "right way".</li>
   <li>You can store arbitrary JavaScript objects in the component.</li>
   <li>The scope is not shared between components, so you don't have to worry about name collisions.</li>
   <li>Works in older versions of Firefox.</li>
  </ul>
 </li>
 <li>Cons:
  <ul>
   <li>You can't use the <code><a href="/en-US/docs/DOM/window" title="DOM/window">window</a></code> object, its members, like <code>alert</code> and <code>open</code>, and many other objects available from inside a window. The functionality isn't lost, however -- you just have to use the XPCOM components directly instead of using convenient shortcuts. Of course, this doesn't matter if you just store data in the component.</li>
   <li>Learning to create XPCOM components takes time.</li>
  </ul>
 </li>
</ul>

<p>There are several articles and books about creating XPCOM components online.</p>

<h3 id="Using_FUEL_Application_object" name="Using_FUEL_Application_object">Using FUEL Application object</h3>

<div class="warning">
<p>The FUEL library has been deprecated as of Firefox 41</p>
</div>

<p>The <a href="/en-US/docs/Toolkit_API/FUEL">FUEL</a> JavaScript library {{ Fx_minversion_inline(3) }} has a simple method for sharing data between windows. The <code>Application</code> object supports a <a href="/en-US/docs/Toolkit_API/extISessionStorage"><code>storage</code></a> property which can be used to store data globally. This method is a simplified form of the XPCOM singleton method.</p>

<pre class="brush:js">Application.storage.set(keyname, data);

var data = Application.storage.get(keyname, default);

where: keyname is a string used to identify the data
       data is the data
       default is the data value to return if keyname does not exists
</pre>

<ul>
 <li>Pros:
  <ul>
   <li>Its the "right way".</li>
   <li>You can store arbitrary JavaScript objects in the component.</li>
   <li>The scope is not shared between components, so you don't have to worry about name collisions.</li>
   <li>No need to build an XPCOM component.</li>
  </ul>
 </li>
 <li>Cons:
  <ul>
   <li>Only works in Firefox 3 or newer.</li>
   <li>You can't use the <code><a href="/en-US/docs/DOM/window" title="DOM/window">window</a></code> object, its members, like <code>alert</code> and <code>open</code>, and many other objects available from inside a window. The functionality isn't lost, however -- you just have to use the XPCOM components directly instead of using convenient shortcuts. Of course, this doesn't matter if you just store data in the component.</li>
  </ul>
 </li>
</ul>

<h3 id="Storing_shared_data_in_preferences" name="Storing_shared_data_in_preferences">Storing shared data in preferences</h3>

<p>If you just need to store a string or a number, writing a whole XPCOM component may be an unnecessary complication. You can use the <a class="external" href="http://www.xulplanet.com/references/xpcomref/ifaces/nsIPrefService.html">preferences service</a> in such cases.</p>

<ul>
 <li>Pros:
  <ul>
   <li>Quite easy to use for storing simple data.</li>
  </ul>
 </li>
 <li>Cons:
  <ul>
   <li>Can't easily be used to store complex data.</li>
   <li>Abusing the preferences service and not cleaning up after yourself can cause <code>prefs.js</code> to grow large and slow down application startup.</li>
  </ul>
 </li>
</ul>

<p>See <a href="/en-US/docs/Code_snippets/Preferences" title="Code_snippets/Preferences">Code snippets:Preferences</a> for detailed description of the preferences system and example code.</p>

<p>Example:</p>

<pre class="brush:js">var prefs = Components.classes["@mozilla.org/preferences-service;1"]
                      .getService(Components.interfaces.nsIPrefService);
var branch = prefs.getBranch("extensions.myext.");
var var1 = branch.getBoolPref("var1"); // get a pref</pre>

<h2 id="See_also" name="See_also">Consulte também</h2>

<ul>
 <li><a href="/en-US/docs/Code_snippets/Dialogs_and_Prompts" title="Code_snippets/Dialogs_and_Prompts">Code snippets:Dialogs</a></li>
</ul>