aboutsummaryrefslogtreecommitdiff
path: root/files/es/xpcomutils.jsm/index.html
blob: 15d8739fdcddc3efa17474dfbf339a7da6c2b5d8 (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
---
title: XPCOMUtils.jsm
slug: XPCOMUtils.jsm
tags:
  - NeedsContent
  - XPConnect
  - páginas_a_traducir
translation_of: Mozilla/JavaScript_code_modules/XPCOMUtils.jsm
---
<p>The <span style="font-family: monospace;">XPCOMUtils</span><code>.jsm</code> JavaScript code module offers utility routines for JavaScript components loaded by the JavaScript component loader.</p>

<p>To use this, you first need to import the code module into your JavaScript scope:</p>

<pre>Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
</pre>

<h2 id="Using_XPCOMUtils">Using XPCOMUtils</h2>

<p>Exposing a JavaScript class as a component using these utility methods requires four key steps:</p>

<ol>
 <li>Import <code>XPCOMUtils.jsm</code>, as explained previously.</li>
 <li>Declare the class (or multiple classes) implementing the component(s).</li>
 <li>Create an array of component constructors.</li>
 <li>Define the <code>NSGetFactory()</code> or <code>NSGetModule()</code> entry point.</li>
</ol>

<h3 id="Pseudocode">Pseudocode</h3>

<p>This section provides some pseudocode that demonstrates how to put together a JavaScript class based on the steps listed above.</p>

<h4 id="Constructor">Constructor</h4>

<p>The constructor is a simple method that handles any required initialization tasks.</p>

<pre class="brush: js">function MyComponent() {
  // initialize the component here
}
</pre>

<h4 id="Class_declaration">Class declaration</h4>

<p>Declare the class prototype, using a form similar to this.</p>

<pre class="brush: js">MyComponent.prototype = {
  // properties required for XPCOM registration:
  classDescription: "unique text description",
  classID:          Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"),
  contractID:       "@example.com/xxx;1",

  // [optional] custom factory (an object implementing nsIFactory). If not
  // provided, the default factory is used, which returns
  // |(new MyComponent()).QueryInterface(iid)| in its createInstance().
  _xpcom_factory: { ... },

  // [optional] an array of categories to register this component in.
  _xpcom_categories: [{
    // Each object in the array specifies the parameters to pass to
    // nsICategoryManager.addCategoryEntry(). 'true' is passed for
    // both aPersist and aReplace params.
    category: "some-category",
    // optional, defaults to the object's classDescription
    entry: "entry name",
    // optional, defaults to the object's contractID (unless
    // 'service' is specified)
    value: "...",
    // optional, defaults to false. When set to true, and only if 'value'
    // is not specified, the concatenation of the string "service," and the
    // object's contractID is passed as aValue parameter of addCategoryEntry.
    service: true,
    // optional array of applications' IDs in the form:
    // [ "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}", ... ]
    // If this is defined, the component is registered in this
    // category only on the specified applications.
    apps: [ ... ]
  }],

  // QueryInterface implementation, e.g. using the generateQI helper
  QueryInterface: XPCOMUtils.generateQI(
    [Components.interfaces.nsIObserver,
     Components.interfaces.nsIMyInterface,
     "nsIFoo",
     "nsIBar" ]),

  // [optional] classInfo implementation, e.g. using the generateCI helper.
  // Will be automatically returned from QueryInterface if that was
  // generated with the generateQI helper.
  classInfo: XPCOMUtils.generateCI(
    {classID: Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"),
     contractID: "@example.com/xxx;1",
     classDescription: "unique text description",
     interfaces: [Components.interfaces.nsIObserver,
                  Components.interfaces.nsIMyInterface,
                  "nsIFoo",
                  "nsIBar"],
     flags: Ci.nsIClassInfo.SINGLETON}),

  // ...component implementation...
};
</pre>

<div class="note">
<p><strong>Note:</strong> The ability to register the component in a category only on specific applications by adding the apps field to a category entry was added in Gecko 2.</p>
</div>

<p>Notice that the <code>QueryInterface()</code> method implemented by the component simply calls the <a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#generateQI()" title="en/JavaScript code modules/XPCOMUtils.jsm#generateQI()"><code>generateQI()</code></a> method provided by the XPCOMUtils code module.</p>

<h4 id="Create_an_array_of_component_constructors">Create an array of component constructors</h4>

<p>You need to create an array that lists the constructors for each component. This array can of course have just one entry:</p>

<pre>var components = [MyComponent];
</pre>

<p>Here, we're calling the array <code>components</code>.</p>

<h4 id="Create_the_NSGetFactory()_or_NSGetModule()_entry_point">Create the NSGetFactory() or NSGetModule() entry point</h4>

<p>Finally, you need to implement the <code>NSGetModule()</code> entry point so Gecko can start up your component:</p>

<pre>// "components" is the array created in the previous section
if ("generateNSGetFactory" in XPCOMUtils)
  var NSGetFactory = XPCOMUtils.generateNSGetFactory(components);  // Gecko 2.0+
else
  var NSGetModule = XPCOMUtils.generateNSGetModule(components);    // Gecko 1.9.x</pre>

<h2 id="Method_overview">Method overview</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <td><code>function <a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#defineLazyGetter()" title="en/JavaScript code modules/XPCOMUtils.jsm#defineLazyGetter()">defineLazyGetter</a>(aObject, aName, aLambda);</code></td>
  </tr>
  <tr>
   <td><code>function <a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#defineLazyModuleGetter()" title="en/JavaScript code modules/XPCOMUtils.jsm#defineLazyModuleGetter()">defineLazyModuleGetter</a>(aObject, aName, aResource, [optional] aSymbol);</code></td>
  </tr>
  <tr>
   <td><code>function <a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#defineLazyServiceGetter()" title="en/JavaScript code modules/XPCOMUtils.jsm#defineLazyServiceGetter()">defineLazyServiceGetter</a>(aObject, aName, aContract, aInterfaceName);</code></td>
  </tr>
  <tr>
   <td><code>function <a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#generateNSGetFactory()" title="en/JavaScript code modules/XPCOMUtils.jsm#generateNSGetFactory()">generateNSGetFactory</a>(componentsArray);</code></td>
  </tr>
  <tr>
   <td><code>function <a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#generateCI()" title="en/JavaScript code modules/XPCOMUtils.jsm#generateCI()">generateCI</a>(classInfo); </code></td>
  </tr>
  <tr>
   <td><code>function <a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#generateQI()" title="en/JavaScript code modules/XPCOMUtils.jsm#generateQI()">generateQI</a>(interfaces);</code></td>
  </tr>
  <tr>
   <td><code>void <a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#importRelative()" title="en/JavaScript code modules/XPCOMUtils.jsm#importRelative()">importRelative</a>(that, path, scope);</code></td>
  </tr>
  <tr>
   <td><code>generator <a href="#IterSimpleEnumerator()" title="en/JavaScript code modules/XPCOMUtils.jsm#IterSimpleEnumerator()">IterSimpleEnumerator</a>(enumerator, interface);</code></td>
  </tr>
  <tr>
   <td><code>generator <a href="#IterStringEnumerator()" title="en/JavaScript code modules/XPCOMUtils.jsm#IterStringEnumerator()">IterStringEnumerator</a>(enumerator);</code></td>
  </tr>
 </tbody>
</table>

<h2 id="Attributes">Attributes</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <td class="header">Attribute</td>
   <td class="header">Type</td>
   <td class="header">Description</td>
  </tr>
  <tr>
   <td><code>categoryManager</code></td>
   <td>{{ interface("nsICategoryManager") }}</td>
   <td>Returns a reference to {{ interface("nsICategoryManager") }}.</td>
  </tr>
 </tbody>
</table>

<h2 id="Methods">Methods</h2>

<h3 id="defineLazyGetter()">defineLazyGetter()</h3>

<p><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">Getter functions in JavaScript</a> give you a way to define a property of an object, but not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed, and if it is never needed, you never pay the cost.</p>

<p>A "lazy getter" provides an additional optimization: the value is calculated the first time the getter is called, and is then cached (or <a href="https://en.wikipedia.org/wiki/Memoization">memoized</a>), so subsequent accesses return the cached value without recalculating it.</p>

<p>This means that you shouldn't use a lazy getter for a property whose value you expect to change, because the getter will not recalculate the value.</p>

<p><code>defineLazyGetter</code> takes three arguments:</p>

<ul>
 <li>the object to define the property on</li>
 <li>the name of the property defined</li>
 <li>the getter function itself, which returns the value and which will be called just once, the first time code tries to access the property.</li>
</ul>

<p>Example for this is seen at bottom of this page <a href="#defineLazyGetter">here</a>.</p>

<pre><code>function defineLazyGetter(
  aObject,
  aName,
  aLambda
);</code> </pre>

<h6 id="Parameters">Parameters</h6>

<dl>
 <dt><code>aObject</code></dt>
 <dd>The object into which to add the new lazy getter function.</dd>
 <dt><code>aName</code></dt>
 <dd>The name of the getter function to create.</dd>
 <dt><code>aLambda</code></dt>
 <dd>A function that returns the value the getter should return. This function is called exactly once. <code>this</code> will reference <code>aObject</code> during execution of the function.</dd>
</dl>

<h3 id="defineLazyModuleGetter()">defineLazyModuleGetter()</h3>

<p>Defines a getter on a specified object for a module. The module will not be imported until first use.</p>

<pre><code>function defineLazyModuleGetter(
  aObject,
  aName,
  aResource,
  aSymbol
);</code> </pre>

<h6 id="Parameters_2">Parameters</h6>

<dl>
 <dt><code>aObject</code></dt>
 <dd>The object to define the lazy getter on.</dd>
 <dt><code>aName</code></dt>
 <dd>The name of the getter to define on <code>aObject</code> for the module.</dd>
 <dt><code>aResource</code></dt>
 <dd>The URL used to obtain the module.</dd>
 <dt><code>aSymbol</code></dt>
 <dd>The name of the symbol exported by the module. This parameter is optional and defaults to <code>aName</code>.</dd>
</dl>

<h3 id="defineLazyServiceGetter()">defineLazyServiceGetter()</h3>

<p>Defines a function on a specified object which acts as a getter for a service. The service isn't obtained until the first time it's used.</p>

<pre>function defineLazyServiceGetter(
  aObject,
  aName,
  aContract,
  aInterfaceName
);
</pre>

<h6 id="Parameters_3">Parameters</h6>

<dl>
 <dt><code>aObject</code></dt>
 <dd>The object into which to add the new lazy service getter function.</dd>
 <dt><code>aName</code></dt>
 <dd>The name of the getter function to create.</dd>
 <dt><code>aContract</code></dt>
 <dd>The contract to use to obtain the service.</dd>
 <dt><code>aInterfaceName</code></dt>
 <dd>The name of the interface to query the service to.</dd>
</dl>

<p> </p>

<h3 id="generateNSGetFactory()">generateNSGetFactory()</h3>

<p> </p>

<p>Generates the <code>NSGetFactory()</code> function along with the factory definition.</p>

<pre>Function generateNSGetFactory(
  componentsArray
);
</pre>

<h6 id="Parameters_4">Parameters</h6>

<dl>
 <dt><code>componentsArray</code></dt>
 <dd>An array of component constructors.</dd>
</dl>

<h6 id="Return_value">Return value</h6>

<p>A function that will return the factory for the components and can be assigned to <code>NSGetFactory</code> global variable.</p>

<p> </p>

<h3 id="generateCI()">generateCI()</h3>

<p> </p>

<p>Generates an {{ interface("nsIClassInfo") }} implementation for a component. The returned object should be assigned to the <code>classInfo</code> property of a JS object, the <code>QueryInterface()</code> function generated by <code>generateQI</code> will return it automatically then.</p>

<pre>function generateCI(
  classInfo
);
</pre>

<h6 id="Parameters_5">Parameters</h6>

<dl>
 <dt>classInfo</dt>
 <dd>An object containing the optional properties <code>interfaces</code>, <code>contractID</code>, <code>classDescription</code>, <code>classID</code>, <code>flags</code>. This parameter should not be the component itself because that would cause a memory leak.</dd>
</dl>

<h6 id="Return_value_2">Return value</h6>

<p>An {{ interface("nsIClassInfo") }} implementation returning the values of the properties from the <code>classInfo</code> parameter in its various properties.</p>

<h6 id="Exceptions_thrown">Exceptions thrown</h6>

<p>This method throws an exception with the message "In generateCI, don't use a component for generating classInfo" if <code>classInfo</code> parameter is an XPCOM component.</p>

<h3 id="generateQI()">generateQI()</h3>

<p>Generates a <code>QueryInterface()</code> function implementation. You need to assign the returned function to the <code>QueryInterface</code> property of a JavaScript object.</p>

<p>When the generated method is invoked on that object, it checks to see if the specified IID is listed in the array specified by the <code>interfaces</code> parameter; if it is, <code>this</code> (that is, the object itself) is returned. Otherwise, <code>null</code> is returned.</p>

<pre>function generateQI(
  interfaces
);
</pre>

<h6 id="Parameters_6">Parameters</h6>

<dl>
 <dt>interfaces</dt>
 <dd>An array of interfaces implemented by the component.</dd>
</dl>

<h6 id="Return_value_3">Return value</h6>

<p>A <code>QueryInterface()</code> function implementation.</p>

<h6 id="Remarks">Remarks</h6>

<p>When you implement an interface that inherits from another one, you should generally list all the base interfaces explicitly, except for {{ Interface("nsISupports") }}. For example, if your component implements {{ Interface("nsIStreamConverter") }}:</p>

<pre class="brush: js">MyComponent.prototype = {
  QueryInterface: XPCOMUtils.generateQI([
    Components.interfaces.nsIRequestObserver,
    Components.interfaces.nsIStreamListener,
    Components.interfaces.nsIStreamConverter,
  ]),

  // ...methods...
}
</pre>

<h3 id="importRelative()">importRelative()</h3>

<p>Imports a JavaScript code module given the calling JavaScript code module's global object (you should specify <code>this</code>) and a path relative to that module. This lets modules bundled in a package load one another without having to hard-code full paths.</p>

<pre>void importRelative(
  that,
  path,
  scope
);
</pre>

<h6 id="Parameters_7">Parameters</h6>

<dl>
 <dt><code>that</code></dt>
 <dd>The JavaScript Object of the calling JavaScript code module's global scope. You should simply pass <code>this</code>.</dd>
 <dt><code>path</code></dt>
 <dd>The relative path of the JavaScript code module to import.</dd>
 <dt><code>scope</code></dt>
 <dd>An optional object to import into; if omitted, the object passed in for the <code>that</code> parameter is used.</dd>
</dl>

<h6 id="Remarks_2">Remarks</h6>

<p>This lets an extension bundle its own JavaScript code modules within itself and have them load one another. For example, if an extension named "MyExtension" bundles <code>foo.jsm</code> and <code>bar.jsm</code>, and foo.jsm needs to load <code>bar.jsm</code>, it can do so like this:</p>

<pre class="deki-transform">Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.importRelative(this, "bar.jsm"); </pre>

<p>In other words: <code>importRelative</code> will only work from other code modules (such as JSM files). It will NOT work from overlay scripts or <code>bootstrap.js</code> or etc. Details can be found here: {{bug("628669")}}</p>

<h3 id="IterSimpleEnumerator()">IterSimpleEnumerator()</h3>

<p>Wraps an {{ Interface("nsISimpleEnumerator") }} instance into a JavaScript generator that can be easily iterated over.</p>

<pre>generator IterSimpleEnumerator(
  enumerator,
  interface
);
</pre>

<h6 id="Parameters_8">Parameters</h6>

<dl>
 <dt><code>enumerator</code></dt>
 <dd>The {{ Interface("nsISimpleEnumerator") }} instance to iterate over.</dd>
 <dt><code>interface</code></dt>
 <dd>The expected interface for each element.</dd>
</dl>

<h6 id="Return_value_4">Return value</h6>

<p>A generator yielding enumerated objects.</p>

<h6 id="Example">Example</h6>

<pre class="brush: js">const nsIFile = Components.interfaces.nsIFile;
for (var file in XPCOMUtils.IterSimpleEnumerator(dir.directoryEntries, nsIFile))
  console.log(file.path);
</pre>

<h3 id="IterStringEnumerator()">IterStringEnumerator()</h3>

<p>Wraps an {{ Interface("nsIStringEnumerator") }} or {{ Interface("nsIUTF8StringEnumerator") }} instance into a JavaScript generator that can be easily iterated over.</p>

<pre>generator IterStringEnumerator(
  enumerator
);
</pre>

<h6 id="Parameters_9">Parameters</h6>

<dl>
 <dt><code>enumerator</code></dt>
 <dd>The {{ Interface("nsIStringEnumerator") }} or {{ Interface("nsIUTF8StringEnumerator") }} instance to iterate over.</dd>
</dl>

<h6 id="Return_value_5">Return value</h6>

<p>A generator yielding enumerated strings.</p>

<h6 id="Example_2">Example</h6>

<pre class="brush: js">for (var section in XPCOMUtils.IterStringEnumerator(iniParser.getSections()))
  console.log(section);
</pre>

<h2 id="Post-registration_callback">Post-registration callback</h2>

<p>The post-registration callback called by <a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#generateModule()" title="en/JavaScript code modules/XPCOMUtils.jsm#generateModule()"><code>generateModule()</code></a> should have the following signature:</p>

<pre>postRegister(
  nsIComponentManager compMgr,
  nsIFile fileSpec,
  componentsArray
);
</pre>

<h6 id="Parameters_10">Parameters</h6>

<dl>
 <dt><code>compMgr</code></dt>
 <dd>An {{ interface("nsIComponentManager") }} instance to use for managing the component.</dd>
 <dt><code>fileSpec</code></dt>
 <dd>An {{ interface("nsIFile") }} instance for... what?</dd>
 <dt><code>componentsArray</code></dt>
 <dd>An array of the components, as passed to <code>generateModule()</code>.</dd>
</dl>

<p>The function doesn't need to return a value.</p>

<h2 id="Pre-unregistration_callback">Pre-unregistration callback</h2>

<p>The pre-unregistration callback passed to <a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#generateModule()" title="en/JavaScript code modules/XPCOMUtils.jsm#generateModule()"><code>generateModule()</code></a> should have the following signature:</p>

<pre>preUnregister(
  nsIComponentManager compMgr,
  nsIFile fileSpec,
  componentsArray
);
</pre>

<h6 id="Parameters_11">Parameters</h6>

<dl>
 <dt><code>compMgr</code></dt>
 <dd>The {{ interface("nsIComponentManager") }} instance to use for managing the component.</dd>
 <dt><code>fileSpec</code></dt>
 <dd>An {{ interface("nsIFile") }} instance for... what?</dd>
 <dt><code>componentsArray</code></dt>
 <dd>The array of components passed to <code>generateModule()</code>.</dd>
</dl>

<p>This function doesn't need to return a value.</p>

<h2 id="Examples">Examples</h2>

<h3 id="defineLazyGetter">defineLazyGetter</h3>

<pre class="brush: js">var myServices = {};
Cu.import('resource://gre/modules/XPCOMUtils.jsm');

//set it up
XPCOMUtils.defineLazyGetter(myServices, 'as', function () { return Cc['@mozilla.org/alerts-service;1'].getService(Ci.nsIAlertsService) });

//when you need to use it
myServices.as.showAlertNotification('chrome://branding/content/icon64.png', 'this was lazyloaded', 'this is a notification from myServices.as', null, null);</pre>

<h2 id="See_also">See also</h2>

<ul>
 <li><a class="internal" href="/en/JavaScript_code_modules/Using" title="en/JavaScript code modules/Using JavaScript code
    modules">Using JavaScript code modules</a></li>
 <li><a class="internal" href="/en/JavaScript_code_modules" title="en/JavaScript code
    modules">JavaScript code modules</a></li>
 <li><a href="http://dxr.mozilla.org/mozilla-central/source/js/xpconnect/loader/XPCOMUtils.jsm">XPCOMUtils.jsm source on DXR</a></li>
</ul>