Search completed in 1.41 seconds.
An Overview of XPCOM
<< PreviousNext >> This is a book about
XPCOM. The book is presented as a tutorial about creating
XPCOM components, but it covers all major aspects, concepts, and terminology of the
XPCOM component model along the way. This chapter provides a quick tour of
XPCOM - an introduction to the basic concepts and technologies in
XPCOM and component development. The brief sections in this chapter introduce the concepts at a very high level, so that we can discuss and use them with more familiarity in the tutorial itself, which describes the creation of a Mozilla component called WebLock. The
XPCOM Solution The Cross Platform Component Object Module (
XPCOM) is a framework which allows developers to break up monolithic software projects into smaller modularized pieces. These pieces, kno...
...se them with more familiarity in the tutorial itself, which describes the creation of a Mozilla component called WebLock. The
XPCOM Solution The Cross Platform Component Object Module (
XPCOM) is a framework which allows developers to break up monolithic software projects into smaller modularized pieces. These pieces, known as components, are then assembled back together at runtime. The goal of
XPCOM is to allow different pieces of software to be developed and built independently of one another. ...
...odule (
XPCOM) is a framework which allows developers to break up monolithic software projects into smaller modularized pieces. These pieces, known as components, are then assembled back together at runtime. The goal of
XPCOM is to allow different pieces of software to be developed and built independently of one another. In order to allow interoperability between components within an application,
XPCOM separates the implementation of a component from the interface, which we discuss in Interfaces. ...
...And 36 more matches
XPCOM
XPCOM is a cross platform component object model, similar to Microsoft COM. It has multiple language bindings, allowing
XPCOM components to be used and implemented in JavaScript, Java, and Python in addition to C++. Interfaces in
XPCOM are defined in a dialect of IDL called XPIDL.
XPCOM itself provides a set of core components and classes, e.g. file and memory management, threads, basic data structures (strings, arrays, variants), etc. The majority of
XPCOM components are not part of this core set and are provided by other parts of the platform (e.g. Gecko or Necko) or by an application or even by an extension. ...
... IDL called XPIDL.
XPCOM itself provides a set of core components and classes, e.g. file and memory management, threads, basic data structures (strings, arrays, variants), etc. The majority of
XPCOM components are not part of this core set and are provided by other parts of the platform (e.g. Gecko or Necko) or by an application or even by an extension. Accessing the Windows Registry Using
XPCOMWhen implementing Windows-specific functionality, it is often useful to access the Windows registry for information about the environment or other installed programs. To this end, there exist
XPCOM interfaces to read and write registry data. This article will show you how to use the available interfaces in several Mozilla products.Aggregating the In-Memory Datasourcealready_AddRefedalready_AddRefe...
... nsCOMPtr allows you to assign in a pointer without AddRefing it.Binary compatibilityIf Mozilla decides to upgrade to a compiler that does not have the same ABI as the current version, any built component may fail. It is a possiblity that is introduced when upgrading to a new compiler without recompiling everything. Effectively, it is a different platform.Bundling multiple binary componentsBinary
XPCOM components are sometimes required to implement low-level features for extensions. Since binary components are linked against a single Gecko SDK, a dependency to a particular version of Gecko is created. If the component uses only "frozen"
XPCOM interfaces, there is a good chance the same binary component will work with different versions of Gecko (version 1.8 and 1.9, for example). The more likel...
...And 31 more matches
Using XPCOM Components
<< PreviousNext >> One of the best ways to begin working with
XPCOM - especially when you are designing the interface to a component that will be used by others, as we do in Starting WebLock - is to look at how clients are already using
XPCOM components. Applications like the Mozilla browser are sophisticated, modularized clients of
XPCOM components. In fact, virtually all of the functionality that you associate with a browser - navigation, window management, managing cookies, bookmarks, security, searching, rendering, and other features - is defined in
XPCOM components and accessed by means of those component interfaces. Mozilla is made of
XPCOM components. ...
...For now, what's important to see is how components like the ones in this section are obtained and used by the Mozilla browser. ...
... - is defined in
XPCOM components and accessed by means of those component interfaces. Mozilla is made of
XPCOM components. This chapter demonstrates how Mozilla uses some of these
XPCOM objects, such as the CookieManager, and shows how access to the WebLock component will be defined. Component Examples You can find out more about how you can use the particular components described here in the
XPCOM API Reference. For now, what's important to see is how components like the ones in this section are obtained and used by the Mozilla browser. Cookie Manager Cookie management is one of the many sets of functionality that is made available to the browser in the form of an
XPCOM component and that can be reused by developers who want similar functionality in their applications. Whenever a user ac...
...And 23 more matches
platform/xpcom - Archive of obsolete content
Implement
XPCOM objects, factories, and services. Usage The
xpcom module makes it simpler to perform three main tasks: Implement
XPCOM object interfaces Implement and register
XPCOM factories Implement and register
XPCOM services If all you need to do is use
XPCOM objects that someone else has implemented, then you don't need to use this module. You can just use require("chrome") to get direct access to the Components object, and access
XPCOM objects from there. Implementing
XPCOM Interfaces This module exports a class called Unknown which implements the fundamental
XPCOM interface nsISupports. By subclassing Unknown, either using standard JavaScript inheritance or using the SDK's heritage module, you can provide your own implementations of
XPCOM interfaces. "Unknown" is named af...
...er using standard JavaScript inheritance or using the SDK's heritage module, you can provide your own implementations of
XPCOM interfaces. "Unknown" is named after the "IUnknown" interface in COM. For example, the add-on below implements the nsIObserver interface to listen for and log all topic notifications: var { Class } = require('sdk/core/heritage'); var { Unknown } = require('sdk/platform/
xpcom'); var { Cc, Ci } = require('chrome') var observerService = Cc['@mozilla.org/observer-service;1']. getService(Ci.nsIObserverService); var StarObserver = Class({ extends: Unknown, interfaces: [ 'nsIObserver' ], topic: '*', register: function register() { observerService.addObserver(this, this.topic, false); }, unregister: function() { observerService.r...
... For example, this add-on defines a subclass of Unknown called HelloWorld that implements a function called hello. By creating a Factory and passing it the contract ID for the HelloWorld component and the HelloWor...
...And 22 more matches
How to build an XPCOM component in JavaScript
If you are looking for Add-on SDK solution for
XPCOM JavaScript components then check out platform/
xpcom module first. This is a "Hello World" tutorial for creating an
XPCOM component in JavaScript. This tutorial does not describe how and why
XPCOM works the way it does, or what every bit of the example code does. That's been detailed elsewhere. This tutorial will show you what you need to do to get a component working in as few and as simple steps as possible. Implementation This example component will expose a single method, which returns the string "Hello World!". Defining the Interface If you want to use your component in other
XPCOM components, you must define the interfaces that you want exposed. If you want to use your component only from JavaScript, you can skip to the next...
...h returns the string "Hello World!". Defining the Interface If you want to use your component in other
XPCOM components, you must define the interfaces that you want exposed. If you want to use your component only from JavaScript, you can skip to the next section. There are many interfaces already defined in Mozilla applications, so you may not need to define a new one. You can browse existing
XPCOM interfaces at various locations in the Mozilla source code, or using
XPCOMViewer, a GUI for browsing registered interfaces and components. You can download an old version of
XPCOMViewer that works with Firefox 1.5 from mozdev mirrors. If an interface exists that meets your needs, then you do not need to write an IDL, or compile a typelib, and may skip to the next section. If you don't find a su...
...r using
XPCOMViewer, a GUI for browsing registered interfaces and components. You can download an old version of
XPCOMViewer that works with Firefox 1.5 from mozdev mirrors. If an interface exists that meets your needs, then you do not need to write an IDL, or compile a typelib, and may skip to the next section. If you don't find a suitable pre-existing interface, then you must define your own.
XPCOM uses a dialect of IDL to define interfaces, called XPIDL. Here's the XPIDL definition for our HelloWorld component: HelloWorld.idl #include "nsISupports.idl" [scriptable, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)] interface nsIHelloWorld : nsISupports { string hello(); }; Note that you must generate a new UUID for each
XPCOM component that you create. See Generating GUIDs for more informa...
...And 22 more matches
XPCOM glue
The
XPCOM Glue is a static library which component developers and embedders can link against. It allows developers to link only against the frozen
XPCOM method symbols and maintain compatibility with multiple versions of
XPCOM. Compiling or linking against
XPCOM headers There are three ways to compile/link against
XPCOM headers/libraries: Frozen linkage: dependent glue (dependent on
xpcom.dll)
XPCOM modules, i.e. extension or XULRunner application components, should use the dependent glue. Code which wishes to use only frozen symbols but can tolerate a load-time dependency on
xpcom.dll should link against
xpcomglue_s.lib and
xpcom.lib. It should not link against
xpcom_core.lib. ...
... Frozen linkage: standalone glue (no DLL dependencies) Note: Support for locating a standalone glue was removed in Gecko 6.0. Use this when you have a custom application where you want to embed Gecko to show webpages in your own window. I.e. ...
...com.dll)
XPCOM modules, i.e. extension or XULRunner application components, should use the dependent glue. Code which wishes to use only frozen symbols but can tolerate a load-time dependency on
xpcom.dll should link against
xpcomglue_s.lib and
xpcom.lib. It should not link against
xpcom_core.lib. This is the case for
XPCOM components, because they are loaded into Mozilla which already has full
XPCOM loaded and initialized. Frozen linkage: standalone glue (no DLL dependencies) Note: Support for locating a standalone glue was removed in Gecko 6.0. Use this when you have a custom application where you want to embed Gecko to show webpages in your own window. I.e. this linkage strategy is used when an embedder needs to bootstrap
XPCOM by finding a compatible GRE on disk and loading it. In o...
...And 19 more matches
XPCOM Objects - Archive of obsolete content
Firefox can be seen as composed of two layers. The largest of the two is a compiled platform, mostly written in C++. On top of it lies the chrome, mostly written in XML, Javascript and CSS. In fact, you can separate the two. We often mention other "Mozilla based applications". Well, those are applications that, simply put, take the underlying platform with perhaps a few changes and additions, and then write their own chrome layer. This lower layer is called XULRunner, and it is a very powerful platform, providing a very robust development base for web-enabled, cross-platform applications. ...
...ns that, simply put, take the underlying platform with perhaps a few changes and additions, and then write their own chrome layer. This lower layer is called XULRunner, and it is a very powerful platform, providing a very robust development base for web-enabled, cross-platform applications. The fact that it allows to easily create OS-independent applications is a big selling point for XULRunner. ...
...ng a very robust development base for web-enabled, cross-platform applications. The fact that it allows to easily create OS-independent applications is a big selling point for XULRunner.
XPCOM is the way in which the two layers (XULRunner and chrome) communicate. Most of the objects and functions in the lower layers are hidden from the chrome; those that need to be publicized are exposed through
XPCOM components and interfaces. You can think of
XPCOM as a reference to all the capabilities available on the lower layers of Firefox. Using
XPCOM components is relatively simple, as you've seen in previous examples. this.obsService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); The Cc object (Components.classes) is an index to static objects and class definitions a...
...And 14 more matches
XPCOMUtils.jsm
Declare the class (or multiple classes) implementing the component(s). Create an array of component constructors. Define the NSGetFactory() or NSGetModule() entry point. Pseudocode This section provides some pseudocode that demonstrates how to put together a JavaScript class based on the steps listed above. ...
... Declare the class (or multiple classes) implementing the component(s). ...
...me pseudocode that demonstrates how to put together a JavaScript class based on the steps listed above. Constructor The constructor is a simple method that handles any required initialization tasks. function MyComponent() { // initialize the component here } Class declaration Declare the class prototype, using a form similar to this. 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_fact...
...And 14 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
should include a link to the MDC list of snippets FIXME: We need to add a part about 'why and how to create your own component' C++/JS This document was authored by Hiroshi Shimoda of Clear Code Inc. and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Mr. Shimoda is a co-author of Firefox 3 Hacks (O'Reilly Japan, 2008). This chapter explains how to use
XPCOM to implement advanced processes using only JavaScript. Introduction JavaScript lacks functions for opening files and character-code conversion, among other things. A different mechanism is needed to perform these functions. Internet Explorer handles this using ActiveX; in Firefox, we use the Cross-Platform Component Object Model, or
XPCOM. Due to deprecation of enablePrivilege this functionali...
...nd character-code conversion, among other things. A different mechanism is needed to perform these functions. Internet Explorer handles this using ActiveX; in Firefox, we use the Cross-Platform Component Object Model, or
XPCOM. Due to deprecation of enablePrivilege this functionality can not be used in web pages. EnablePrivilege is disabled in Firefox 15 and will be removed in Firefox 17. About
XPCOM XPCOM is a framework for developing platform-independent components. ...
...ng ActiveX; in Firefox, we use the Cross-Platform Component Object Model, or
XPCOM. Due to deprecation of enablePrivilege this functionality can not be used in web pages. EnablePrivilege is disabled in Firefox 15 and will be removed in Firefox 17. About
XPCOM XPCOM is a framework for developing platform-independent components. Components developed in line with that framework are referred to as
XPCOM components, and sometimes the components are simply referred to as
XPCOMs. Firefox itself includes a great number of
XPCOM components, and they can be used in extensions as well. Sometimes an extension will be packaged with a special
XPCOM component developed specifically for it. Note: If you're developing components in C++ or other compiled languages, be sure to include binaries for every plat...
...And 10 more matches
Using XPCOM Utilities to Make Things Easier
<< PreviousNext >> This chapter goes back over the code you've already created in the first part of the tutorial (see webLock1.cpp in the previous chapter) and uses
XPCOM tools that make coding a lot easier and more efficient. It also introduces a basic string type that is used with many of the APIs in both
XPCOM and Gecko. To begin with, the first section describesC++ macros that can replace a lot of the code in webLock1.cpp. Much of the code created to get the software recognized and registered as a component can be reduced to a small data structure and a single macro.
XPCOM Macros The
XPCOM framework includes a number of macros for making C++ development easier. Though they overlap somewhat (e.g., high-level macros expand to other macros), they fall into the following gene...
...But there are only a few places in that code that are unique to the WebLock component, and it was a lot of typing. ...
...ing up the generic component code. But there are only a few places in that code that are unique to the WebLock component, and it was a lot of typing. To write a different component library, you could copy the listing at the end of the chapter, change very little, and paste it into a new project. To avoid these kinds of redundancies, to regulate the way generic code is written, and to save typing,
XPCOM providesgeneric module macros that expand into the module code you've already seen. Since these macros expand into "generic" implementations, they may not offer as much flexibility as you have when you are writing your own implementation. But they have the advantage of allowing much more rapid development. To get an idea about how much can be handled with the macros described in this section, co...
...And 10 more matches
Creating XPCOM components
Next >> This guide is about Gecko, and about creating
XPCOM components for Gecko-based applications. Though the emphasis is on the practical steps you take to make your C++ code into a component that can be used in Gecko, we hope that these steps will also give us an occasion to discuss all of the tools, techniques, and technologies that make up
XPCOM. Accordingly, the book is arranged so that you can follow along and create your own components or learn about different
XPCOM topics individually, as in a reference work. ...
...Add-ons should try to use the new Add-on SDK as much as possible; however, there may be cases when it's unavoidable. ...
... as in a reference work. For example, the introduction includes a discussion of components and what they are, and the first chapter - in which you compile the basic code and register it with Mozilla - prompts a discussion of the relationship between components and modules, of
XPCOM interfaces, and of the registration process in general. Note: In general, you should try to avoid having to create
XPCOM components. ...
...And 10 more matches
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
Obsolete since Gecko 4.0This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Warning: This technology is obsolete. No active maintainer has stepped forward, and the code broke in Firefox 4. The code has been removed from the Mozilla source tree. XULRunner ships with the Java
XPCOM component, which allows Java code to interact with
XPCOM objects. As you will see in this article, working with
XPCOM objects in Java is not that much different than doing so in C++. Prerequisites Java 1.4.2 or newer XULRunner 1.8.0.1 or newer Embedding In order to embed Mozilla in your Java application, you will need to add the library MozillaInterfaces.jar (located in xulrunner/sdk/lib folder) to...
... To start embedding, we use the methods provided by the Mozilla singleton class. ...
... If your code cannot find the GRE and keeps throwing FileNotFoundExceptions during the getGREPathWithProperties(...) call, check whether you already regi...
...And 9 more matches
XPCOM changes in Gecko 2.0
Several changes that affect
XPCOM component compatibility are taking place in Gecko 2. This article details those changes, and provides suggestions for how to update your code. No more frozen interfaces There are no longer any frozen interfaces; from now on, all interfaces are subject to change. Documentation will be updated as time allows to remove references to interfaces being "frozen" or "unfrozen." Component registration The way
XPCOM components are registered changed in Gecko 2. Prior to Gecko 2, during component registration, all binary and JavaScript component files were loaded and called, asking them to register themselves. If you used
XPCOMUtils.jsm, some of this was hidden from you, but it was still there. Starting in Gecko 2, however, components are registered using manifest files,...
...However, it's very easy to do, and you can actually support both types of registration for backward compatibility. Component manifests All component registration is now handled through manifest files. ...
...ame chrome.manifest currently used to register chrome. XPT files The path of any XPT files must be listed explicitly in a manifest using an interfaces directive: interfaces components/mycomponent.xpt JavaScript components The registration information for JavaScript components is no longer located in the component itself; instead, it's located in the manifest. The component is loaded only when the
XPCOM component manager needs to create a component. chrome.manifest: # The {classID} here must match the classID in mycomponent.js component {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} components/mycomponent.js contract @foobar/mycomponent;1 {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} category profile-after-change MyComponent @foobar/mycomponent;1 The JavaScript code no longer exports a NSGetModule() function.
...And 9 more matches
Introduction to XPCOM for the DOM
The understanding of the content of this document is a requirement to read the rest of the DOM Hacking Guide. ...
...The understanding of the content of this document is a requirement to read the rest of the DOM Hacking Guide. ...
...The understanding of the content of this document is a requirement to read the rest of the DOM Hacking Guide. ...
...And 9 more matches
XPCOM reference
This reference describes the interfaces and functions provided by the
XPCOM library. In addition, it details the various helper classes and functions, as well as the components, provided by the
XPCOM glue library. The contents herein are oriented primarily toward extension developers and people embedding
XPCOM in other projects. If you're working on a module in the Mozilla codebase that's compiled with the MOZILLA_INTERNAL_API flag set, some of these APIs -- the string functions and classes in particular -- are not the ones you should be using. See the
XPCOM internal string guide for documentation of the internal string API used within the Mozilla codebase. ...
...There are currently three folder classes - nsLocalMailFolder, nsImapMailFolder, and nsNewsFolder. ...
...There are currently three folder classes - nsLocalMailFolder, nsImapMailFolder, and nsNewsFolder. ...
...And 9 more matches
Avoiding leaks in JavaScript XPCOM components
nce this article was written. E. g. in Firefox 3, a cycle collector was introduced and refined in later versions, and Mozilla is currently working on a generational garbage collector for JS. This article needs to be updated to reflect the changes and the cases where they help. Take every information on this site with a grain of salt, although most concepts and best practices still apply. Using
XPCOM in JavaScript (also known as XPConnect) is an environment where memory management issues are not obvious. There are no calls to malloc and free and no reference counting. Despite this, it's easy to write JavaScript code that leaks. It's easy to write leaky code in any garbage-collected language. But it's even easier in this environment because some of the objects you're dealing with are reference...
...ls to malloc and free and no reference counting. Despite this, it's easy to write JavaScript code that leaks. It's easy to write leaky code in any garbage-collected language. But it's even easier in this environment because some of the objects you're dealing with are reference-counted behind the scenes. Programmers writing and reviewing JavaScript code in Mozilla should understand how code using
XPCOM in JavaScript can leak so that they can avoid leaks. This document attempts to help them do so, first by explaining the underlying concepts, and second by describing a number of common JavaScript patterns that cause leaks. Basics of memory management Creating objects that are not a fixed size for the lifetime of the program (global variables) or a fixed size for the lifetime of a function (stac...
...a given object and it's uncertain which one will need to last the longest. Reference counting Reference counting is a simple solution to the problem of allowing multiple owners to influence the lifetime of an object. In this strategy, the object has a member that is the number of other objects that "own" it. When this count goes to zero, the object destroys itself. This is the strategy used by
XPCOM, partly because it can be used through a very simple API, AddRef and Release. In C++, we use nsCOMPtr to help manage ownership, and we use macros to implement AddRef and Release. The major problem with reference counting is that it can cause leaks through ownership cycles. If object A owns object B, and object B owns object A, then neither one will ever be destroyed. This tends to be solved in on...
...And 7 more matches
XPCOM guide
These articles provide tutorials and usage documentation for
XPCOM, including how to use it in your own projects and how to build
XPCOM components for your Firefox add-ons and the like. Avoiding leaks in JavaScript
XPCOM componentsProgrammers writing and reviewing JavaScript code in Mozilla should understand how code using
XPCOM in JavaScript can leak so that they can avoid leaks. ...
...ons and the like. Avoiding leaks in JavaScript
XPCOM componentsProgrammers writing and reviewing JavaScript code in Mozilla should understand how code using
XPCOM in JavaScript can leak so that they can avoid leaks. ...
...ponentsProgrammers writing and reviewing JavaScript code in Mozilla should understand how code using
XPCOM in JavaScript can leak so that they can avoid leaks. ...
...And 7 more matches
How to build a binary XPCOM component using Visual Studio
On Windows, the SDK is built using a Microsoft compiler, so you need to use one too. This tutorial uses Microsoft's free Visual C++ Express and the sample project in the next paragraph. ...
...On Windows, the SDK is built using a Microsoft compiler, so you need to use one too. This tutorial uses Microsoft's free Visual C++ Express and the sample project in the next paragraph. ...
...On Windows, the SDK is built using a Microsoft compiler, so you need to use one too. This tutorial uses Microsoft's free Visual C++ Express and the sample project in the next paragraph. ...
...And 7 more matches
NS_InitXPCOM2
aBinDirectory [in] The directory containing the component registry and runtime libraries. ...
... aBinDirectory [in] The directory containing the component registry and runtime libraries. ...
... aBinDirectory [in] The directory containing the component registry and runtime libraries. ...
...And 7 more matches
Standalone XPCOM - Archive of obsolete content
Warning: The content of this article may be out of date. These instructions were last updated in 2000. Standalone
XPCOM is a tree configuration that builds a minimal set of libraries (shared mostly) that can be used to get all features of
XPCOM. The contents of this standalone
XPCOM in general are: NSPR : mozilla/nsprpub
XPCOM : mozilla/
xpcom NOTE 1:
XPCOM APIs are not frozen yet. By
XPCOM 1.0 release they will be. NOTE 2:
XPCOM Standalone differs from the
XPCOM built with Mozilla. Hence cannot be used with the Mozilla browser. ...
...mal set of libraries (shared mostly) that can be used to get all features of
XPCOM. The contents of this standalone
XPCOM in general are: NSPR : mozilla/nsprpub
XPCOM : mozilla/
xpcom NOTE 1:
XPCOM APIs are not frozen yet. By
XPCOM 1.0 release they will be. NOTE 2:
XPCOM Standalone differs from the
XPCOM built with Mozilla. Hence cannot be used with the Mozilla browser. ...
...This should get built by default. ...
...And 6 more matches
XPCOM array guide
Mozilla has many array classes because each array is optimized for a particular usage pattern. This guide describes the available arrays as well as the enumerator classes that can be used to get to them. In this document the term Array refers to a container for multiple objects with a numeric, zero-based index. The standard array classes are: nsIArray - a scriptable container for scriptable
XPCOM objects. This array is read-only, and the interface does not provide any methods that will allow adding and removing members. nsIMutableArray - a scriptable container for scriptable
XPCOM objects, which allows addition and removal of member objects. This interface actually derives from nsIArray. nsTArray<T> - a C++ class which provides a typesafe container for objects or primitive types (pointe...
...le on nsTArray for arrays instantiated with pointer types. Some other arrays: FallibleTArray, AutoFallibleTArray, InfallibleTArray, AutoInfallibleTArray, nsTObserverArray, nsAutoTObserverArray. ...
...allibleTArray, InfallibleTArray, AutoInfallibleTArray, nsTObserverArray, nsAutoTObserverArray. This handy chart may make it easier to understand the different arrays: Class Data Type Scriptable? Typesafe? Can be modified? Built in buffer? Ownership nsIArray
XPCOM object Yes No No No Reference Counted, Weak/Strong nsIMutableArray
XPCOM object Yes No Yes No Reference Counted, Weak/Strong nsCOMArray<T>
XPCOM object No Yes Yes* No Reference Counted, Strong nsTArray<T> Any that has a default constructor and copy constructor No Yes Yes* No Can hold objects directly, in which case it owns them. When holding pointers, doesn't own the pointer. nsAutoTArray<T,...
...And 6 more matches
Core XPCOM functions
XPCOM provides a number of global functions which are used to initialize and shut down the
XPCOM library, as well as to allocate memory, get access to services, and to instantiate interfaces. ...
...
XPCOM provides a number of global functions which are used to initialize and shut down the
XPCOM library, as well as to allocate memory, get access to services, and to instantiate interfaces. ...
...
XPCOM provides a number of global functions which are used to initialize and shut down the
XPCOM library, as well as to allocate memory, get access to services, and to instantiate interfaces. ...
...And 5 more matches
XPCOM ABI
XPCOM ABI is the binary interface of
XPCOM components. While
XPCOM components written in a scripting language (such as JavaScript) can be moved across platforms (such as Windows and OS X) without adaptation, those written in a compiled language (such as C++) require recompilation when moving to a different platform. Often, compiled
XPCOM components are called 'binary' or 'native'. A binary
XPCOM component consists of an .xpt file which fits all platforms and a DLL (.dll on Windows, .so on Unix) which is platform-specific and has a certain ABI. Only applications which use this ABI could use this
XPCOM component. To put it simply, an
XPCOM component built for a specific ABI would only be compatible with Firefox, Thunderbird or other XULRunner application built for the same ABI. ABI Nami...
...fits all platforms and a DLL (.dll on Windows, .so on Unix) which is platform-specific and has a certain ABI. Only applications which use this ABI could use this
XPCOM component. To put it simply, an
XPCOM component built for a specific ABI would only be compatible with Firefox, Thunderbird or other XULRunner application built for the same ABI. ...
...- SPARC series ia64 - Itanium series {TARGET_COMPILER_ABI}[Platforms] represents the compiler ABI and may be either: msvc - Microsoft Visual C++ n32 - IRIX 6 C++ Compiler gcc2 - GNU C++ Compiler 2.x gcc3 - GNU C++ Compiler 3.x or 4.x sunc - Sun C++ Compiler ibmc - IBM C++ Compiler For example: Firefox built with the GNU C++ Compiler 4.0.0 for the Intel Pentium processor would have
XPCOM ABI of x86-gcc3 The
XPCOM ABI string can be retrieved programmatically by using the nsIXULRuntime interface. To retrieve the ABI of your Firefox or Thunderbird, open the Error Console (accessible through Tools | Error Console) and evaluate the following JavaScript code: Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULRuntime) .
XPCOM...
...And 5 more matches
JS XPCOM - Archive of obsolete content
Here are a few useful snippets of code for dealing with
XPCOM components in JavaScript. Contract IDs A contract ID is a unique name for an
XPCOM object. They are used to create or access well-known objects in
XPCOM. Interfaces Every
XPCOM object implements one or more interfaces. An interface is simply a list of constants and methods that can be called on the object, an example is nsIFile. Every
XPCOM object must implement the nsISupports interface. Accessing
XPCOM components from JavaScript
XPCOM objects are either created as new instances (each creation gives you a completely new COM object) or as services (each access gives you the same COM object, often called a singleton). ...
...ery
XPCOM object must implement the nsISupports interface. Accessing
XPCOM components from JavaScript
XPCOM objects are either created as new instances (each creation gives you a completely new COM object) or as services (each access gives you the same COM object, often called a singleton). Whether you must create a new instance or access as a service depends on the contract. In order to get an
XPCOM object you need to know the contract ID of the object and the interface that you wish to use on it. Creating an instance of a component The preferred method of creating
XPCOM instances is via the Components.Constructor helper. For example, var nsFile = Components.Constructor("@mozilla.org/file/local;1", "nsIFile", "initWithPath"); var file = new nsFile(filePath); They can also be created an...
... = new nsFile(filePath); They can also be created and initialized manually: var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsIFile); file.initWithPath(filePath); This creates a new instance of the object with contract ID @mozilla.org/file/local;1 and allows you to call methods from the nsIFile interface on it. Getting an
XPCOM service var preferences = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService); You can then call any methods in the nsIPrefService interface on the preferences object. Getting a different interface for a component Some components implement more than one interface. Sometimes JavaScript is clever enough to know ...
...And 4 more matches
XPCOM Interfaces - Archive of obsolete content
Calling Native Objects By using XUL we can build a complex user interface. We can attach scripts which modify the interface and perform tasks. However, there are quite a number of things that cannot be performed directly with JavaScript. For example, if we wanted to create a mail application, we would need to write scripts which would connect to mail servers to retrieve and send mail. JavaScript does not have the capability to do such things. The only way to handle this would be to write native code that would get mail. ...
...we wanted to create a mail application, we would need to write scripts which would connect to mail servers to retrieve and send mail. JavaScript does not have the capability to do such things. The only way to handle this would be to write native code that would get mail. We also need to have a way for our scripts to call the native code easily. Mozilla provides such a method which involves using
XPCOM (Cross-platform Component Object Model). Mozilla provides many
XPCOM components and interfaces. So, in most cases, you don't need to write native code for yourself. After learning this section, you can search suitable interfaces using XULPlanet
XPCOM Reference About
XPCOM Mozilla is constructed from a collection of components, each of which performs a certain task. For example, there is a comp...
...se a component by accessing it using the functions we know from the interface. In Mozilla, interfaces are usually preceded by 'nsI' or 'mozI' so that they are easily recognized as interfaces. For example, the nsIAddressBook is the interface for interacting with an address book, nsISound is used for playing files and nsILocalFile is used for files. For more interfaces in Mozilla, see Interfaces.
XPCOM components are typically implemented natively, which means that they generally do things that JavaScript cannot do itself. However, there is a way in which you can call them, which we will see shortly. We can call any of the functions provided by the component as described by the interfaces it implements. For example, once we have a component, we can check if it implements nsISound, and, if so, w...
...And 4 more matches
NS_InitXPCOM3
<<
XPCOM API Reference Summary The NS_Init
XPCOM3 function initiates use of
XPCOM in the calling process with support for statically defined
XPCOM modules. #include "ns
XPCOM.h" nsresult NS_Init
XPCOM3( nsIServiceManager** aResult, nsIFile* aBinDirectory, nsIDirectoryServiceProvider* aAppFileLocationProvider, nsStaticModuleInfo const* aStaticModules, PRUint32 aStaticModuleCount ); Parameters aResult [out] The resulting
XPCOM service manager. You may pass null if you are not interested in this return value. The service manager may alternatively be accessed by calling NS_GetServiceManager. The resulting interface pointer is AddRef'd upon return and must either be Release'd explicitly or passed to NS_Shutdown
XPCOM when the application is finished with
XPCOM. aBinDirect...
...ager. The resulting interface pointer is AddRef'd upon return and must either be Release'd explicitly or passed to NS_Shutdown
XPCOM when the application is finished with
XPCOM. aBinDirectory [in] The directory containing the component registry and runtime libraries. Pass null to specify that the current working directory should be used. aAppFileLocationProvider [in] The object to be used by
XPCOM to locate application specific directories and files (e.g., the user profile, the component registry, etc.). This parameter may be nsnull. aStaticModules [in] An array of nsStaticModuleInfo objects. ...
...sed by
XPCOM to locate application specific directories and files (e.g., the user profile, the component registry, etc.). This parameter may be nsnull. aStaticModules [in] An array of nsStaticModuleInfo objects. Passing null causes the default (built-in) static modules to be registered, if present. aStaticModuleCount [in] The number of elements in aStaticModules. Return Values The NS_Init
XPCOM3 function returns NS_OK if successful. Otherwise, it returns an error code. Some of the possible errors are documented below: NS_ERROR_NOT_INITIALIZED Indicates that static globals were not yet initialized, which may happen if this method is called before
XPCOM's static initialization code executes. ...
...And 4 more matches
NS_ShutdownXPCOM
Calling this method triggers the "
xpcom-shutdown" notification to be dispatched to observers. Once this function has been called, the nsIComponentManager and nsIServiceManager will refuse to return object instances. History This function was finalized for Mozilla 0.9.6. ...
...Calling this method triggers the "
xpcom-shutdown" notification to be dispatched to observers. Once this function has been called, the nsIComponentManager and nsIServiceManager will refuse to return object instances. History This function was finalized for Mozilla 0.9.6. ...
...Calling this method triggers the "
xpcom-shutdown" notification to be dispatched to observers. Once this function has been called, the nsIComponentManager and nsIServiceManager will refuse to return object instances. History This function was finalized for Mozilla 0.9.6. ...
...And 4 more matches
Using LDAP XPCOM with XULRunner - Archive of obsolete content
See the Build_Documentation for more information about how to build XULRunner. When Configuring Build Options, just add: ac_add_options --enable-ldap to your .mozconfig file. ...
...See the Build_Documentation for more information about how to build XULRunner. When Configuring Build Options, just add: ac_add_options --enable-ldap to your .mozconfig file. ...
...See the Build_Documentation for more information about how to build XULRunner. When Configuring Build Options, just add: ac_add_options --enable-ldap to your .mozconfig file. ...
...And 3 more matches
Creating a Python XPCOM component
Creating Applications with Mozilla already provides a tutorial for making a simple JavaScript or C++ component (implementing the nsISimple interface). Here is how to make the same component in Python using Py
XPCOM. (Note that some details may be missing.) Preparation If a binary of Py
XPCOM is not available, you will need to build it - see Building Py
XPCOM. Tip: you can achieve a copy of binary of Py
XPCOM from PythonExt; simply unpack xpi and take everything you need. If you wish to use Py
XPCOM from a normal Python executable, you will need to tell Python where it can find the Py
XPCOM library. This is probably best done by setting a PYTHONPATH variable pointing at the 'bin/python' directory in the application. This is not necessary when your components are loaded by Mozilla as the Py...
... take everything you need. If you wish to use Py
XPCOM from a normal Python executable, you will need to tell Python where it can find the Py
XPCOM library. This is probably best done by setting a PYTHONPATH variable pointing at the 'bin/python' directory in the application. This is not necessary when your components are loaded by Mozilla as the Python loader modifies sys.path. Then you can import
xpcom in any Python module (mostly, in your component). Defining the interface Make a file named "nsIPySimple.idl" to define the interface: #include "nsISupports.idl" [scriptable, uuid(2b324e9d-a322-44a7-bd6e-0d8c83d94883)] interface nsIPySimple : nsISupports { attribute string yourName; void write( ); void change(in string aValue); }; This is the same as the nsISimple interface used here...
...../xpidl -m typelib -w -v -I /usr/share/idl/mozilla/ nsIPySimple.idl On Windows you must point to the idl directory as part of your Mozilla build. For example: xpidl.exe -m typelib -w -v -I C:\source\mozilla\obj-i686-pc-mingw32\dist\idl foo.idl xpidl will then create nsIPySimple.xpt, which should be placed correctly (e.g., in the 'components' directory). Implementing the component Unlike C++, Py
XPCOM does much of the work for you. Make a file named "py_simple.py" for the actual code (again, in the 'components' directory): from
xpcom import components, verbose class PySimple: #PythonTestComponent _com_interfaces_ = components.interfaces.nsIPySimple _reg_clsid_ = "{c456ceb5-f142-40a8-becc-764911bc8ca5}" _reg_contractid_ = "@mozilla.org/PySimple;1" def __init__(self): se...
...And 3 more matches
Detailed XPCOM hashtable guide
Keys can be disjunct (i.e. you can store entries with keys 1, 5, and 3000). ...
...items. Each item has a key that identifies the item. Items are found, added, and removed from the hashtable by using the key. Hashtables may seem like arrays, but there are important differences: Array Hashtable Keys: integer: arrays are always keyed on integers, and must be contiguous. any type: almost any datatype can be used as key, including strings, integers,
XPCOM interface pointers, IIDs, and almost anything else. Keys can be disjunct (i.e. you can store entries with keys 1, 5, and 3000). Lookup Time: O(1): lookup time is a simple constant O(1): lookup time is mostly-constant, but the constant time can be larger than an array lookup Sorting: sorted: stored sorted; iterated over in a sorted fashion. unsorted: stored unsorted; ...
...ing> <ns(C)StringHashKey, nsString> <nsIDHashKey, nsString> <nsISupportsHashKey, nsString> Complex (structures, etc.) nsTHashtable<...> PLDHash The PLDHash implementation is a fairly low-level implementation, written in C. It is extremely flexible, but requires some time to understand and use. A basic guide is included here, but you should read most of
xpcom/glue/pldhash.h if you intend to use PLDHash. The C++ wrappers for PLDHash (see below) are often much easier and safer to use in C++ code, as many potential casting errors are easily avoided. You must declare an entry struct type, deriving from PLDHashEntryHdr. This entry struct should contain whatever data you wish to store in the hashtable (any pointer or fixed-length data type). Note: because ...
...And 3 more matches
PyXPCOM
Py
XPCOM allows for communication between Python and
XPCOM, such that a Python application can access
XPCOM objects, and
XPCOM can access any Python class that implements an
XPCOM interface. Py
XPCOM is actively used in ActiveState Komodo products, for example. With Py
XPCOM, a developer can talk to
XPCOM or embed Gecko from a Python application. Py
XPCOM is similar to Java
XPCOM (Java-
XPCOM bridge) or XPConnect (JavaScript-
XPCOM bridge). Mozilla defines many external interfaces available to embeddors and component developers. Py
XPCOM provides access to these interfaces as Python interfaces. Py
XPCOM also contains several classes that provide access to functions for initializing and shutting down
XPCOM and Gecko from Python, as well as some
XPCOM helper functions. Documentation ...
...COM bridge). Mozilla defines many external interfaces available to embeddors and component developers. Py
XPCOM provides access to these interfaces as Python interfaces. Py
XPCOM also contains several classes that provide access to functions for initializing and shutting down
XPCOM and Gecko from Python, as well as some
XPCOM helper functions. Documentation Building Py
XPCOM The instructions for building Py
XPCOM. Creating a Python
XPCOM component An example of how to create a simple
XPCOM component with Python. Getting to know Py
XPCOM Py
XPCOM is a bridging technology between
XPCOM and Python. This article gives you a head start to Py
XPCOM. NOTE: The links to Part II and III of th...
...ow to create a simple
XPCOM component with Python. Getting to know Py
XPCOM Py
XPCOM is a bridging technology between
XPCOM and Python. This article gives you a head start to Py
XPCOM. NOTE: The links to Part II and III of this series are broken and I cannot find them on the IBM site. Please update this page if/when the links can be found. History Py
XPCOM was initially developed by ActiveState Tool Corporation, and came out of their Komodo project. Current releases are now integrated with the Mozilla build system. ...
...And 3 more matches
XPCOM tasks
Warning: The content of this article may be out of date. It was last edited in 2003 and is probably of historical interest only. The Role of
XPCOM The
XPCOM module roughly parallels the C/C++ standard libraries. It overlaps them significantly, but goes beyond them in capabilities.
XPCOM sits above the standard libraries. Its role is to extend them with facilities tailored to
XPCOM development in general, and specifically the needs of Mozilla. Like the standard libraries,
XPCOM must be a fairly self-contained library, so as not to encumber clients with any unnecessary external dependencies. ...
...s beyond them in capabilities.
XPCOM sits above the standard libraries. Its role is to extend them with facilities tailored to
XPCOM development in general, and specifically the needs of Mozilla. Like the standard libraries,
XPCOM must be a fairly self-contained library, so as not to encumber clients with any unnecessary external dependencies. Changes to the Build Hierarchy There are things in
XPCOM that don't belong there. There is likely to be code outside of
XPCOM that should be in it. There is code above
XPCOM that should be below it. P3 I/O functionality (except for the filespec facility) probably doesn't belong in
XPCOM; perhaps it should be moved to netwerk P3 The `Twips' units routines (or perhaps all routines) in "nsUnitConversion.h" probably belong in layout. P3 nsStringTokeniz...
...OM that should be below it. P3 I/O functionality (except for the filespec facility) probably doesn't belong in
XPCOM; perhaps it should be moved to netwerk P3 The `Twips' units routines (or perhaps all routines) in "nsUnitConversion.h" probably belong in layout. P3 nsStringTokenizer probably belongs in the parser. 5.1 3rd party code that doesn't use any services from our tree should be below
XPCOM; particularly, code
XPCOM could exploit, e.g., expat Berkeley db Changes to APIs, Functionality, and Implementations The following items are listed (very) roughly in their order of importance, i.e., fixing observers is the first thing I want to do. P1 Various threading issues, e.g., Too many locks. See bug 13009. Not enough locks. See bug 5795, bug 12755, and bug 12755. P1 We would li...
...And 2 more matches
XPCOM primitive
Also, certain APIs, such as nsITransferable.setTransferData(), require primitives. ...
...Also, certain APIs, such as nsITransferable.setTransferData(), require primitives. ...
...Also, certain APIs, such as nsITransferable.setTransferData(), require primitives. ...
...Also, certain APIs, such as nsITransferable.setTransferData(), require primitives. ...
Using XPCOM without chrome - Archive of obsolete content
Using sdk
XPCOM With the low-level module sdk/platform/
xpcom , it's possible to exclude chrome and
XPCOMUtils in some cases. Below is an example for the
XPCOM bookmark observer. Examples Bookmarks Observer Normally, a bookmark observer would require Chrome Components and
XPCOMUtils as described in the following links: (Observing changes to bookmarks and tags) , (Creating Event Targets). However, with the sdk module , we can remove this need. Below is an example, where we extend the
xpcom module's Unknown class with an nsINavBookmarkObserverinterface and one of its optional interface methods (onItemchanged). We can then create an object from it and add it as an observer to the bookmarks service. ...
...tags) , (Creating Event Targets). However, with the sdk module , we can remove this need. Below is an example, where we extend the
xpcom module's Unknown class with an nsINavBookmarkObserverinterface and one of its optional interface methods (onItemchanged). We can then create an object from it and add it as an observer to the bookmarks service. ...
...ple, where we extend the
xpcom module's Unknown class with an nsINavBookmarkObserverinterface and one of its optional interface methods (onItemchanged). We can then create an object from it and add it as an observer to the bookmarks service. ...
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
Mozilla versions 0.9.2 and higher and Netscape versions 6.1 and higher. It does not cover Netscape 6 and 6.01 Introduction Plugins that used to take advantage of being scriptable via LiveConnect in 4.x Netscape browsers lost this possibility in the new world. The main reason for this is that there is no guarantee of Java compatibility on a binary level due to the jri/jni switch. The new Mozilla
XPCOM architecture allows
XPCOM components be scriptable via a different mechanism called XPConnect. We leverage some of these ideas to help you make your Netscape Communicator 4.x plugins exposed to JavaScript in Mozilla based browsers. In order to make it still possible to script plugins, some changes have been made to the Mozilla code. The changes allow to make existing 4.x plugins scriptable with o...
...MS DevStudio MIDL must not be used. (Let's assume 'TestPlugin' as a plugin name-place holder.) Compile nsITestPlugin.idl with the idl compiler. This will generate nsITestPlugin.h and nsITestPlugin.xpt files. Put nsITestPlugin.xpt to the Components folder. Build nptestplugin.dll with nsITestPlugin.h included for compiling scriptable instance class implementai...
...Plugin.xpt files. Put nsITestPlugin.xpt to the Components folder. Build nptestplugin.dll with nsITestPlugin.h included for compiling scriptable instance class implementaion. Put nptestplugin.dll to the Plugins folder. Related sources The full sample plugin code can be found in the Mozilla source tree under modules/plugin/samples/4x-scriptable/ IBM Developer Works has published a good article on
XPCOM. Examples Example 1. Sample .idl file #include "nsISupports.idl" [scriptable, uuid(bedb0778-2ee0-11d5-9cf8-0060b0fbd8ac)] interface nsITestPlugin : nsISupports { void nativeMethod(); }; Example 2. Scriptable instance class #include "nsITestPlugin.h" #include "nsIClassInfo.h" // We must implement nsIClassInfo because it signals the // Mozilla Security Manager to allow calls from JavaScri...
JavaXPCOM
Java
XPCOM allows for communication between Java and
XPCOM, such that a Java application can access
XPCOM objects, and
XPCOM can access any Java class that implements an
XPCOM interface. Java
XPCOM is not actively maintained. With Java
XPCOM, a developer can talk to
XPCOM or embed Gecko from a Java application. Java
XPCOM is very similar to XPConnect (JavaScript-
XPCOM bridge), and uses XPIDL. Note: Java
XPCOM was included in XULRunner up through version 1.9.2. It has been removed in XULRunner 2, and is not actively maintained. Documentation Java
XPCOM Development How to get and build the source, as well as how to view and report bugs. Sample code There are several Java test applications checked in to the tree that give examp...
...nner up through version 1.9.2. It has been removed in XULRunner 2, and is not actively maintained. Documentation Java
XPCOM Development How to get and build the source, as well as how to view and report bugs. Sample code There are several Java test applications checked in to the tree that give examples on how to embed Gecko or init
XPCOM from within Java. Embedding Mozilla in a Java Application using Java
XPCOM XULRunner ships with the Java
XPCOM component, which allows Java code to interact with
XPCOM objects. As you will see in this article, working with
XPCOM objects in Java is not that much different than doing so in C++. View All... Community View Mozilla Embedding forums.
... XULRunner ships with the Java
XPCOM component, which allows Java code to interact with
XPCOM objects. As you will see in this article, working with
XPCOM objects in Java is not that much different than doing so in C++. View All... Community View Mozilla Embedding forums... ...
XPCOM glue classes
NS ConvertASCIItoUTF16 externalClass DeclarationNS ConvertUTF16toUTF8 externalClass DeclarationNS ConvertUTF8toUTF16 externalClass DeclarationNS LossyConvertUTF16toASCII externalClass DeclarationNS_ConvertASCIItoUTF16Class DeclarationNS_ConvertUTF16toUTF8Class DeclarationNS_ConvertUTF8toUTF16Class DeclarationNS_LossyConvertUTF16toASCIIClass DeclarationNS_OVERRIDENS_OVERRIDE is a macro which allows C++ code in Mozilla to specify that a method is intended to override a base class method. ...
...t must be released, typically on destruction of the object.</t>nsAutoRefTraitsnsAutoRefTraits<t> is a template class describing traits of resources held by objects of class nsAutoRef<T> and/or nsCountedRef<T>.</t>nsAutoStringClass DeclarationnsAutoString (External)Class DeclarationnsCAutoStringClass DeclarationnsCAutoString (External)Class DeclarationnsCOMPtrThis utility class simplifies managing
XPCOM interface references from C++ code.nsCountedRefnsCountedRef<t> is a template class implementing an object that takes a strong reference to a reference-counted resource that must be released, typically on destruction of the object.</t>nsCStringClass DeclarationnsCString externalClass DeclarationnsCStringContainer (External)Class Declaration nsCStringEncodingThe nsCStringEncoding enumeration de...
...torage.nsEmbedStringThe nsEmbedString concrete class provides a way to construct a nsAString object that allocates null-terminated storage.nsFixedCStringClass DeclarationnsFixedStringClass DeclarationnsLiteralCString (External)Class DeclarationnsLiteralString (External)Class DeclarationnsMemoryThe nsMemory class provides static helper routines to manage memory. These routines allow easy access to
XPCOM's global nsIMemory implementation without having to go through the service manager to get it.nsPromiseFlatCStringClass DeclarationnsPromiseFlatStringClass DeclarationnsRefPtrRefPtr (formerly known as nsRefPtr, see bug 1207245) is a general class to implement reference counting pointers for objects. It is similar to nsCOMPtr, but does not require that the type be an
XPCOM interface. Like with nsC...
XPCOM Examples - Archive of obsolete content
Window Management This example contains RDF datasource that will be seen in the later section. You might skip this example for the time being, except when you have already had that knowledge. Creating a Window menu The list of currently open Mozilla windows can be used as an RDF datasource. This allows you to create a Window menu with a list of the currently open windows in the application. The datasource for this is rdf:window-mediator. ...
...In this case, we just use the instanceof operator to accomplish this. Finally, an item is added to the menu for the cookie. The host, name and value properties of the cookie are used for this. Menus have an appendItem() function which can be used to add an item to the menu, given a label and a value. See also More examples are available below. Code snippets http://kb.mozillazine.org/Category:
XPCOM_example_code Next, we'll look at how to create trees. << PreviousNext >> ...
Accessing the Windows Registry Using XPCOM
Support in Firefox 1.5 or newer In Firefox 1.5, a new API was added, nsIWindowsRegKey, which provides extensive registry functionality. ...
... Support in Firefox 1.5 or newer In Firefox 1.5, a new API was added, nsIWindowsRegKey, which provides extensive registry functionality. ...
How To Pass an XPCOM Object to a New Window
A more useful example is available in the source code: toolkit/components/help/content/contextHelp.js#61 If you want to be able to call functions within an
XPCOM object from a XUL window's code, you can do so if you pass the
XPCOM object as one of the arguments to the window creation method. For example: var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]. ...
...thod. For example: var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]. getService(Components.interfaces.nsIWindowWatcher); var win = ww.openWindow(null, "chrome://myextension/content/debug.xul", "debug history", "chrome,centerscreen,resizable", myObject); Note in this example that myObject is passed to the openWindow() method; you can pass any
XPCOM object (or any other value, for that matter) in this way. To access the
XPCOM object from the window's code, you can access the window.arguments[] array, as shown in the example below: Components.utils.reportError(String(window.arguments[0])); This will produce output similar to "[xpconnect wrapped nsIMy
XPCOMObject]". ...
Interfacing with the XPCOM cycle collector
This is a quick overview of the cycle collector introduced into
XPCOM for Firefox 3, including a description of the steps involved in modifying an existing C++ class to participate in
XPCOM cycle collection. If you have a class that you think is involved in a cyclical-ownership leak, this page is for you. The intended audience is Mozilla C++ developers. What the cycle collector does The cycle collector spends most of its time accumulating (and forgetting about) pointers to
XPCOM objects that might be involved in garbage cycles. This is the idle stage of the collector's operation, in which special variants of nsAutoRefCnt register and unregister themselves very rapidly with the collector, as they pass through a "suspicious" refcount event (from N+1 to N, for nonzero N). Periodically ...
...t is important that it only run from near the top-loop of the program. It will not crash if there are extra owning pointers, but it will find itself unable to account for the reference counts it finds in the owned objects, so may fail to collect cycles. How to make your classes participate The interface between the cycle collector and your classes can be accessed directly using the contents of
xpcom/base/nsCycleCollector.h, but there are convenience macros for annotating your classes in
xpcom/glue/nsCycleCollectionParticipant.h that are much easier to use. In general, assuming you are modifying class nsFoo with two nsCOMPtr edges mBar and mBaz, the process can be distilled to a few simple modifications: Include the header nsCycleCollectionParticipant.h in both nsFoo.h and nsFoo.cpp. Add ...
PlXPCOM
pl
XPCOM (Perl
XPCOM) provides language bindings letting you use
XPCOM from Perl code. The resources here provide information about this language binding and how to use it. ...
... pl
XPCOM (Perl
XPCOM) provides language bindings letting you use
XPCOM from Perl code. The resources here provide information about this language binding and how to use it. ...
RbXPCOM
You can find additional information using the resource links below. ...
...You can find additional information using the resource links below. ...
Troubleshooting XPCOM components registration
There are several common reasons that registration can fail: A component that is a binary (shared library) fails to load A JavaScript component has parsing errors The shared library loaded correctly, but registration was not successful Did Registration Succeed? It is important to not misdiagnose the problem. You can be certain that a component has failed to register by going to the Error Console and evaluating Components.classes["contract-id"].name where contract-id is your contract ID. If the response is your contract ID instead of an error, the component was successfully registered and this is the wrong page. ...
...all Firefox windows! set NSPR_LOG_MODULES=nsNativeModuleLoader:5 set NSPR_LOG_FILE=C:\Path\to\logfile "C:\Program Files\Mozilla Firefox\firefox.exe" Examining this log for warning and errors may provide valuable clues why the component failed to load. If using Firefox 4 / XULRunner 2.0, make sure that your extension is unpacked and you declared the binary component in your chrome.manifest. See
XPCOM changes in Gecko 2.0 Parsing Errors in JavaScript Components The most common reason for components written in JavaScript to fail is that there are parsing errors. These parsing errors should show up in the Error Console if chrome errors are enabled. To learn more about enabling chrome errors, see "How can I see errors in my code" in the Extension FAQs. Registration Failure If the module is lo...
XPCOM Glue without mozalloc
Starting with XULRunner 2.0, the frozen linkage dependent glue (
xpcomglue_s.lib on Windows, lib
xpcomglue_s.a on Linux and Mac) is dependent on the new infallible memory allocation routines (mozalloc). Since these routines didn't exist prior to XULRunner 2.0,
XPCOM components that link against the frozen linkage dependent glue will not be compatible with XULRunner applications prior to 2.0. The solution is to link against
xpcomglue_s_nomozalloc instead (
xpcomglue_s_nomozalloc.lib on Windows, lib
xpcomglue_s_nomozalloc.a on Linux and Mac). This library is new in XULRunner 2.0, and it's identical to
xpcomglue_s, except that it's compiled without mozalloc. Simply change all references to "
xpcomglue_s" in your compiler and linker flags to "
xpcomglue_s_nomozalloc". Resulting
XPCOM componen...
XPCOM hashtable guide
This is the simplified version of the Detailed
XPCOM hashtable guide. Everything you need to know is probably on this page. Also note that mfbt/HashTable.h now exists. It is a lot faster than the
XPCOM hashtables due to more inlining and templating, and the API is arguably better. What Is a Hashtable? A hashtable is a data construct that stores a set of items. Each item has a key that identifies the item. Items are found, added, and removed from the hashtable by using the key. Hashtables may seem like arrays, but there are important differences: Array Hashtable Keys: integer: arrays are always keyed on integers, and must be contiguous. any type: almost any datatype can be used as key, including strings, integers,
XPCOM interface pointers, IIDs, and...
Standard XPCOM components
There are a number of components provided in the standard implementation of
XPCOM; these are as follows. nsCategoryManagerThe
XPCOM Category Manager.nsDirectoryServiceThe
XPCOM Directory Service. This service returns the locations of "well known" directories in an OS-independent manner. For instance, it can give you the path of the system's temporary directory, desktop directory, current working directory, and so on.nsLocalFileA component implementing nsILocalFile. nsObserverServiceThe
XPCOM Observer Service.nsScriptableInputStreamA component implementing nsIScriptableInputStream. ...
XPCOM Interface Reference
This is a reference to the
XPCOM interfaces provided by the Mozilla platform. Component; nsIPrefBranchExtensionManager (Toolkit)IAccessible2IAccessibleActionIAccessibleApplicationIAccessibleComponentIAccessibleEditableTextIAccessibleHyperlinkIAccessibleHypertextIAccessibleImageIAccessibleRelationIAccessibleTableIAccessibleTable2IAccessibleTableCellIAccessibleTextIAccessibleValueIDispatchIJSDebuggeramIInstallCallbackamIInstallTriggeramIWebInstallInfoamIWebInstallListeneramIWebInstallPromptamIWebInstallerimgICacheimgIContainerimgIContainerObserverimgIDecoderimgIDecoderObserverimgIEncoderimgILoaderimgIRequestinIDOMUtilsjsdIStackFramemozIAsyncFaviconsmozIAsyncHistorymozIColorAnalyzermozIJSSubScriptLoadermozIPersonalDictionarymozIPlaceInfomozIPlacesAutoCompletemozIRegistrymozIRepresentative...
XPCOM Interface Reference by grouping
Grouping and category names were made by somewhat arbitrary decision by the author. (I'm fully aware that this will be a great point of discussion and probably will end in tears, but since I'm the first person to apparently take a swing at this, I get first dibs.) The primary sections consist of: Browser This section contains elements associated with the view pane or the content of the "browser window" proper. ...
XPCOM string functions
NS_CStringAppendDataThe NS_CStringAppendData function appends data to the existing value of a nsACString instance. ...
XPCOM Thread Synchronization
Mutex::Lock()) has a matching function in NSPR (PR_Lock()). This is no accident, as mozilla:: primitives are merely bare-minimum wrappers around NSPR's. This article covers the API of Mozilla synchronization only. For a higher-level introduction to thread synchronization, see Introduction_to_NSPR. Quick reference: Difference between nsAutoLock API and new API Old construction Note: This is deprecated code that is shown only to compare with approved code. ...
XPCOM category image-sniffing-services
In versions of Firefox prior to Firefox 3, extensions could add decoders for new image types. However, such decoders relied on servers sending correct MIME types; images sent with incorrect MIME types would not be correctly displayed. In Firefox 3, a new
XPCOM category was added in bug 391667 to allow "third-party"
XPCOM components to identify images based on their content. If Mozilla's built-in image code cannot identify an image, then any
XPCOM components implementing the nsIContentSniffer interface may register under the "image-sniffing-services" category, and will be queried to determine the MIME type of the image being downloaded. Note: This category was removed. See Bug 813787 - Remove support for image-sniffing-services. ...
Index
Found 1275 pages: # Page Tags and summary 1
XPCOM Add-ons, Extensions, Landing, Mozilla,
XPCOM XPCOM is a cross platform component object model, similar to Microsoft COM. It has multiple language bindings, allowing
XPCOM components to be used and implemented in JavaScript, Java, and Python in addition to C++. 2 Accessing the Windows Registry Using
XPCOM Add-ons, Code snippets, Extensions, NeedsClassification, Windows Registry When implementing Windows-specific functionality, it is often useful to access the Windows registry for information about the environment or other installed programs. To this end, there exist
XPCOM interfaces to read and write registry data. This article will show you how to use the available interfaces in s...
..., it is often useful to access the Windows registry for information about the environment or other installed programs. To this end, there exist
XPCOM interfaces to read and write registry data. This article will show you how to use the available interfaces in several Mozilla products. 3 Aggregating the In-Memory Datasource RDF No summary! ...
...summary! 4 Binary compatibility
XPCOM If Mozilla decides to upgrade to a compiler that does not have the same ABI as the current version, any built component may fail. It is a possiblity that is introduced when upgrading to a new compiler without recompiling everything. Effectively, it is a different platform. 5 Bundling multiple binary components Binary
XPCOM components are sometimes required to implement low-level features for extensions. Since binary components are linked against a single Gecko SDK, a dependency to a particular version of Gecko is created. If the component uses only "frozen"
XPCOM interfaces, there is a good chance the same binary component will work with different versions of Gecko (version 1.8 and 1.9, for example). The more likel...
...And 824 more matches
Component Internals
The most common type of component is one that is written in C++ and compiled into a shared library (a DLL on a Windows system or a DSO on Unix). ...
...The most common type of component is one that is written in C++ and compiled into a shared library (a DLL on a Windows system or a DSO on Unix). ...
... a client of
XPCOM components, this chapter discusses components from the perspective of the software developer. Read on to see how components are generally implemented in
XPCOM, or you can skip to the next chapter, where the WebLock component tutorial takes you step by step through the component creation process. XXX mediawiki...XXX sucks Creating Components in C++ Let's start by examining how
XPCOM components are written in C++. The most common type of component is one that is written in C++ and compiled into a shared library (a DLL on a Windows system or a DSO on Unix). The illustration below shows the basic relationship between the shared library containing the component implementation code you write and the
XPCOM framework itself. In this diagram, the outer boundary is that of the modul...
...And 42 more matches
Starting WebLock
nsIObserver. Observersare objects that are notified when various events occur. Using them is a good way for objects to pass messages to each other without the objects having explicit knowledge of one another. Usually, there is one object notifying a group of observers. ...
...If your object would like to register for this or other events, it first must implement the nsIObserver interface. ...
...n nsISupports aSubject, in string aTopic, in wstring aData); There aren't really any restrictions on what the three parameters (aSubject, aTopic and aData) may represent. These parameters are defined according to the event being observed. For example, in the case of the
XPCOM shutdown observation, aSubject and aData are not defined, and aTopic is defined as the string "
xpcom-shutdown". If your object would like to register for this or other events, it first must implement the nsIObserver interface. Once you do this, the observer service implementing nsIObserverService can notify your object of registered events by means of this interface, as in the figure below. The Observer Interfaces The above figure shows the observer service maintaining a list of all register...
...And 40 more matches
Index - Archive of obsolete content
n them. 94 net/url No summary! 95 net/xhr Provides access to XMLHttpRequest functionality. 96 places/bookmarks Create, modify, and retrieve bookmarks. 97 places/favicon Helper functions for working with favicons. 98 places/history Access the user's browsing history. 99 platform/
xpcom Implement
XPCOM objects, factories, and services. 100 preferences/event-target Add-on SDK Listen to changes to the Preferences system in Firefox. 101 preferences/service Add-on SDK, Jetpack, SDK Access the Preferences system in Firefox. 102 remote/child Module, Reference, SDK Enables an SDK module loaded into a child proces...
... Add-on SDK No summary! 163 Modifying Web Pages Based on URL Add-on SDK No summary! 164 Modifying the Page Hosted by a Tab Add-on SDK No summary! 165 Open a Web Page Add-on SDK No summary! 166 Troubleshooting No summary! 167 Unit Testing Add-on SDK, JPM No summary! 168 Using
XPCOM without chrome Bookmarks, Chrome, SDK,
XPCOM No summary! 169 Using third-party modules (jpm) Addon-SDK, JPM First, while in the root of your add-on, install the package that contains the modules you want to use: 170 Bootstrapped extensions Add-ons, Extensions, Firefox 4, Gecko 2.0, Guide, Localization No summary! 171 Code snippets ...
... the local file name/path. ...
...And 35 more matches
Creating the Component Code
<< PreviousNext >> This chapter goes over the basic code required to handle the relationship between your component and
XPCOM. Having the component found and registered properly is the goal of this first chapter of the tutorial. In the subsequent chapters, we can begin to work on the example WebLock component functionality itself. Use the Calculator (After Learning Long Division) You have to write a fair amount of code to create a component library that gets loaded into
XPCOM. An
XPCOM component needs to implement at least three interfaces that
XPCOM requires, and often others as well. ...
...rk on the example WebLock component functionality itself. Use the Calculator (After Learning Long Division) You have to write a fair amount of code to create a component library that gets loaded into
XPCOM. An
XPCOM component needs to implement at least three interfaces that
XPCOM requires, and often others as well. There is more code in this chapter than you'll eventually need, however. Using
XPCOM Utilities to Make Things Easier shows some simpler and more elegant ways to create an
XPCOM component using generic macros, and this chapter is more about learning the basics. As in grade school when you learned long division, better tools like calculators come after you figure out what's actually happening. In this case, the long-hand implementation gives us an opportunity to talk about various ...
... What We'll Be Working On The component we'll be working on in this book controls a special mode in your browser that prevents users from leaving the current domain or a set of safe domains. Once enabled, this "weblock" mode is password protected and persists until it is turned off by the password holder. ...
...And 29 more matches
Reference Manual
This section will help you if you're already familiar with nsCOMPtr but you need details. If you've never use nsCOMPtrs before, you might want to read the Getting Started Guide first. If you're trying to fix a broken build, the FAQ might lead you to the answer more quickly. The Basics Design An nsCOMPtr is designed to be a complete replacement for raw
XPCOM interface pointers where they are used as owning references. Almost any place you could use a raw
XPCOM interface pointer, you should be able to use an nsCOMPtr. An nsCOMPtr is the exact same size and shape as a raw
XPCOM interface pointer. It can be used as a member variable without introducing bloat. Most of the work of being an owning reference can be done in the constructor, destructor, and assignment operators of nsCOMPtr. Whene...
... could use a raw
XPCOM interface pointer, you should be able to use an nsCOMPtr. An nsCOMPtr is the exact same size and shape as a raw
XPCOM interface pointer. It can be used as a member variable without introducing bloat. Most of the work of being an owning reference can be done in the constructor, destructor, and assignment operators of nsCOMPtr. Whenever you `point' the nsCOMPtr at a different
XPCOM object (by assignment or initialization), it must Release its old value, if any, and AddRef the new. At its own destructor time it must Release as well. nsCOMPtr only does exactly the work you would have done, if you always remembered to do the right thing. Safety Features Type Safeguards It is an invariant of nsCOMPtr that it holds the
XPCOM-correct interface pointer for it's underlying type. Fo...
...ctor time it must Release as well. nsCOMPtr only does exactly the work you would have done, if you always remembered to do the right thing. Safety Features Type Safeguards It is an invariant of nsCOMPtr that it holds the
XPCOM-correct interface pointer for it's underlying type. For example, an nsCOMPtr<nsIFoo> will always hold the pointer that would be returned by QueryInterface, when querying an
XPCOM object for its nsIFoo interface. In debug builds, if you subvert this invariant with one of the assignment forms that doesn't call QueryInterface, nsCOMPtr will assert at runtime in the bad assignment. // Given two un-related interfaces |nsIFoo| and |nsIBar|... nsIBar* bar = ...; // ... nsCOMPtr<nsIFoo> foo = bar; // NS_ASSERTION: "QueryInterface needed" // ...even ...
...And 22 more matches
Getting Started Guide
eference Manual or the FAQ. Don't worry; the Getting Started Guide is short. Introduction What is nsCOMPtr? nsCOMPtr is a tool to help prevent leaks. nsCOMPtr is a "smart pointer". It is a template class that acts, syntactically, just like an ordinary pointer in C or C++, i.e., you can apply * or -> to it to "get to" what it points at. ...
...is a tool to help prevent leaks. nsCOMPtr is a "smart pointer". It is a template class that acts, syntactically, just like an ordinary pointer in C or C++, i.e., you can apply * or -> to it to "get to" what it points at. nsCOMPtr is smart in that, unlike a raw C++ pointer to an
XPCOM object, nsCOMPtr manages AddRef, Release, and QueryInterface for you. nsCOMPtr is defined in the source files:
xpcom/base/nsCOMPtr.h
xpcom/base/nsCOMPtr.cpp ...though you probably don't want to look in there, just yet. With nsCOMPtr, you can write code that is shorter, cleaner, clearer, and safer, than you can with raw
XPCOM interface pointers.
XPCOM Basics: Ownership and Reference Counting This is a quick refresher on some fundamental issues of
XPCOM. You should already know this, and should be able to j...
...od place to learn about the basic rules and reasoning behind COM is in Essential COM by Don Box. Don Box gets into more of the details, traps, and pitfalls of COM in Effective COM. You should also have a reasonable knowledge of C++. Probably the three most helpful books on this topic are The C++ Programming Language by Bjarne Stroustrup, Effective C++, and More Effective C++ by Scott Meyers. All
XPCOM objects are allocated on the heap. Clients don't get to know much about the implementation of any such object. They reference it only through a pointer to an `interface', i.e., the static type of the pointer is a pointer to an abstract base class, the actual object pointed to is a class derived from that abstract base class. The
XPCOM object is said to `implement that interface'. The client's ref...
...And 19 more matches
A bird's-eye view of the Mozilla framework
the contents into a DOM tree, and handles the layout and rendering of the document pages. The NGLayout engine also parses XUL UI controls into a DOM tree and handles rendering of the UI. Core Services Modules such as the NGLayout engine comprise the core application services available to other core modules, and XUL packages Core application modules are implemented as a set of one or more
XPCOM (Cross-Platform COM) objects.
XPCOM Object Model Before getting into the details of the UI example, it's helpful to have a basic understanding of the
XPCOM object model. Mozilla architectural modules are comprised of groups of related
XPCOM objects that provide services to and access services from each other through dynamically queryable interfaces. Object Model At a Glance Mozilla dynamicall...
...he
XPCOM object model. Mozilla architectural modules are comprised of groups of related
XPCOM objects that provide services to and access services from each other through dynamically queryable interfaces. Object Model At a Glance Mozilla dynamically loads and integrates core modules and XUL packages into the runtime environment on startup. Once loaded, a module or package has full access to the
XPCOM objects of all the other modules in the runtime environment. The ability to dynamically integrate modules and packages at startup is a powerful benefit of the object model, which defines a module as a set of one or more
XPCOM objects calledcomponents. These objects provide services to client packages and modules and access services provided by other modules through dynamically queryable interface...
...ce, and if available, accesses that service through an interface defined in XPIDL (Cross-Platform IDL), derived from the CORBA IDL. The XPIDL interface description is independent of the programming language used to implement the object itself. For example, a JavaScript object or C++ class could both implement the same XPIDL interface. Scripting languages such as JavaScript cannot directly access
XPCOM components, but access them indirectly using XPConnect. XPConnect also provides a required layer for
XPCOM components written in a scripting language. Let's consider a Resource Description Framework (RDF) example, where RDF is a framework for describing and interchangingmetadata, that is, information about information. In this example, we're interested in the RDF sub-graph underlying theContents...
...And 15 more matches
Setting up the Gecko SDK
tup information for the Gecko Software Development Kit (SDK) used to build the WebLock component in this tutorial. The following four sections tell the developer how to download and organize the Gecko SDK and create a new project in which components like WebLock can be created. Downloading and Setting the SDK The Gecko SDK provides all of the tools, headers, and libraries that you need to build
XPCOM Components. The SDK is available for Windows, Linux, and Mac operating systems, and versions for other operating systems are being developed, and can be retrieved from as a single archive from the following platform-specific locations (Need correction for last version (now 1.9.2.8). There is now separate archive with gecko-sdk, just xul-runner-sdk.): Linux: http://ftp.mozilla.org/pub/mozi....8...
...emember to adjust the settings described here (e.g., in the Building a Microsoft Visual Cpp Project section below) to point to this new location. When you extract the SDK, it should have the layout seen below: Layout of the Extracted SDK The directories represent different modules in the SDK. For example, the headers for networking are all located in the necko directory, and the headers that
XPCOM requires are in the
XPCOM directory. This directory structure makes build scripts slightly more complicated (since there will be many different include paths), but it helps to organize the parts of the SDK meaningfully. The two top level header files are special. The file mozilla-config.h lists all of the defines used in the SDK. Including this header file in your project ensures that the compon...
...r includes in your component's source code. Each module directory is divided into three subdirectories: Module Subdirectories The bin directory contains static libraries, dynamic libraries, and in some cases tools that may be useful in development. The idl directory contains the public IDL files exported by the module. The includes directory contains C++ header files used by your component. ...
...And 14 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
For complex extensions, it may be necessary to create components in C++ that provide additional functionality. Reasons why you might want to include C++ components in your extension include: Need for high-performance beyond what can be delivered by JavaScript code. Use of third-party libraries written in C or C++. Use of Mozilla interfaces that are not exposed via
XPCOM (e.g. NSPR). Note: With the modern JIT Javascript Engine in Gecko and js-ctypes more extension code can be written only in JavaScript than ever before. Please consider all of your options carefully before deciding to use native code (C++) in your extension. In addition, binary components need to be recompiled for every major Firefox release, which can be frustrating. This a...
...or every major Firefox release, which can be frustrating. This article describes how to set up the development environment for a large, complex Firefox extension with any or all of the above-mentioned requirements. I should also stress that you do not have to build Mozilla or use the Mozilla build system if you want to create C++ components for Mozilla. If you are just looking to create an
XPCOM component or two, this is probably overkill, and you might want to take a look at this guide instead. On the other hand, if you are an experienced developer or team, and you know that you are going to build a large, complex extension, you would do well to consider the approach described in this article. One final note: I've only tried these techniques inside Firefox, but they'll probably w...
... All the tools for building are available built-in, and therefore all you have to do is run some commands in the terminal. You can find full instructions for almost any OS here. Structuring Your Project Mozilla includes a number of complex extensions that are integrated into its build process. It has thus been necessary to solve all of the issues involved in creating and registering
XPCOM components, building JAR files and manifests, installing the lot into the Firefox extensions/ directory and so forth. So it behooves us to piggyback on this infrastructure to build our extension. First of all, think of a catchy name for your extension and create a directory with that name under the /mozilla/extensions/ directory. Use only lowercase letters. You should see a bunch of other ...
...And 10 more matches
Language bindings
An
XPCOM Language Binding is a bridge between a particular language and
XPCOM to provide access to
XPCOM objects from that language, and to let modules written in that language be used as
XPCOM objects by all other languages for which there are
XPCOM bindings. More specifically, an
XPCOM language binding: Enables access to
XPCOM objects from that language (where access means reading/writing/creating
XPCOM objects as well as calling methods on them). Exposes modules written in the bound language as
XPCOM objects, thereby enabling all other languages for which
XPCOM bindings exist to access these modules. Since the
XPCOM layer itself is written in C/C++, its API can be accessed out-of-the-box using C or C++. ...
... The following bridging layers are currently available: Components objectThe Components object is the object through which XPConnect functionality is reflected into JavaScript. ...
...These exception objects may be thrown when implementing
xpcom interfaces in JavaScript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will.Components.IDComponents.ID is a constructor that creates native objects tha...
...And 10 more matches
nsIXPConnect
void flagSystemFilenamePrefix(in string aFilename...
...int32 interfaceCount, [array, size_is(interfaceCount)] in nsIIDPtr interfaceArray); jsval evalInSandboxObject(in AString source, in JSContextPtr cx, in nsIXPConnectJSObjectHolder sandbox, in PRBool returnStringOnly); Native code only! void flagSystemFilenamePrefix(in string aFilenamePrefix, in PRBool aWantNativeWrappers); void GarbageCollect(); [noscript,not
xpcom] void getCaller(out JSContextPtr aJSContext, out JSObjectPtr aObject); JSVal getCOWForObject(in JSContextPtr aJSContext, in JSObjectPtr aParent, in JSObjectPtr aWrappedObj); Native code only! Obsolete since Gecko 2.0 void getDefaultSecurityManager(out nsIXPCSecurityManager aManager, out PRUint16 flags); nsIXPCFunctionThisTranslator getFunctionThisTranslator(in nsIIDRe...
...ext, in JSObjectPtr aParent, in JSObjectPtr aWrappedObj); Native code only! ...
...And 10 more matches
nsISupportsArray
xpcom/ds/nsISupportsArray.idlScriptable Please add a summary to this article. Inherits from: nsICollection Last changed in Gecko 1.7 Method overview boolean AppendElements(in nsISupportsArray aElements); Violates the
XPCOM interface guidelines nsISupportsArray clone(); void Compact(); void DeleteElementAt(in unsigned long aIndex); void DeleteLastElement(in nsISupports aElement); nsISupports ElementAt(in unsigned long aIndex); Violates the
XPCOM interface guidelines boolean EnumerateBackwards(in nsISupportsArrayEnumFunc aFunc, in voidPtr aData); Violates the
XPCOM interface guidelines boolean EnumerateForwards(in nsISupportsArrayEnumFunc aFunc, in voidPtr aData); Violates the
XPCOM interface guidelines boolean Equals([const] in nsISupportsArray other); Violates...
... nsISupports ElementAt(in unsigned long aIndex); Violates the
XPCOM interface guidelines boolean EnumerateBackwards(in nsISupportsArrayEnumFunc aFunc, in voidPtr aData); Violates the
XPCOM interface guidelines boolean EnumerateForwards(in nsISupportsArrayEnumFunc aFunc, in voidPtr aData); Violates the
XPCOM interface guidelines boolean Equals([const] in nsISupportsArray other); Violates the
XPCOM interface guidelines long GetIndexOf(in nsISupports aPossibleElement); long GetIndexOfStartingAt(in nsISupports aPossibleElement, in unsigned long aStartIndex); long GetLastIndexOf(in nsISupports aPossibleElement); long IndexOf([const] in nsISupports aPossibleElement); Violates the
XPCOM interface guidelines long IndexOfStartingAt([const] in nsISupports aPossibleElement, in unsigned lon...
...GetIndexOf(in nsISupports aPossibleElement); long GetIndexOfStartingAt(in nsISupports aPossibleElement, in unsigned long aStartIndex); long GetLastIndexOf(in nsISupports aPossibleElement); long IndexOf([const] in nsISupports aPossibleElement); Violates the
XPCOM interface guidelines long IndexOfStartingAt([const] in nsISupports aPossibleElement, in unsigned long aStartIndex); Violates the
XPCOM interface guidelines boolean InsertElementAt(in nsISupports aElement, in unsigned long aIndex); Violates the
XPCOM interface guidelines boolean InsertElementsAt(in nsISupportsArray aOther, in unsigned long aIndex); Violates the
XPCOM interface guidelines long LastIndexOf([const] in nsISupports aPossibleElement); Violates the
XPCOM interface guidelines boolean MoveElement(in long aFrom, in...
...And 9 more matches
Refcount tracing and balancing
step that analyzes the resulting log to help a developer figure out where refcounting went wrong. How to build for refcount tracing Build with --enable-debug or --enable-logrefcnt. How to run with refcount tracing on There are several environment variables that can be used. First, you select one of three environment variables to choose what kind of logging you want. You almost certainly want
XPCOM_MEM_REFCNT_LOG. NOTE: Due to an issue with the sandbox on Windows (bug 1345568), refcount logging currently requires the MOZ_DISABLE_CONTENT_SANDBOX environment variable to be set.
XPCOM_MEM_REFCNT_LOG Setting this environment variable enables refcount tracing. If you set this environment variable to the name of a file, the log will be output to that file. You can also set it to 1 to log ...
...able to be set.
XPCOM_MEM_REFCNT_LOG Setting this environment variable enables refcount tracing. If you set this environment variable to the name of a file, the log will be output to that file. You can also set it to 1 to log to stdout or 2 to log to stderr, but these logs are large and expensive to capture, so you probably don't want to do that. WARNING: you should never use this without
XPCOM_MEM_LOG_CLASSES and/or
XPCOM_MEM_LOG_OBJECTS, because without some filtering the logging will be completely useless due to how slow the browser will run and how large the logs it produces will be.
XPCOM_MEM_COMPTR_LOG This environment variable enables logging of additions and releases of objects into nsCOMPtrs. This requires C++ dynamic casts, so it is not supported on all platforms. How...
...f objects into nsCOMPtrs. This requires C++ dynamic casts, so it is not supported on all platforms. However, having an nsCOMPtr log and using it in the creation of the balance tree allows AddRef and Release calls that we know are matched to be eliminated from the tree, so it makes it much easier to debug reference count leaks of objects that have a large amount of reference counting traffic. ...
...And 8 more matches
WebIDL bindings
reason we want to catch and rethrow exceptions from SetSomeNumber, say. aCallback.SetSomeNumber(2*number, rv, eRethrowExceptions); if (rv.Failed()) { // The exception is now stored on rv. This code MUST report // it usefully; otherwise it will assert. } } External interfaces External interfaces are represented in C++ as objects that XPConnect knows how to unwrap to. This can mean
XPCOM interfaces (whether declared in XPIDL or not) or it can mean some type that there's a castable native unwrapping function for. The C++ type to be used should be the nativeType listed for the external interface in the Bindings.conf file. The exact representation depends on how the type is being used. Arguments become nsIFoo*. Return values can be already_AddRefed<nsIFoo> or nsIFoo* as desired.
...ject this way will not invoke its __init method or init method. Implementing a WebIDL object in JavaScript To implement a WebIDL interface in JavaScript, first add a WebIDL file, in the same way as you would for a C++-implemented interface. To support implementation in JS, you must add an extended attribute JSImplementation="CONTRACT_ID_STRING" on your interface, where CONTRACT_ID_STRING is the
XPCOM component contract ID of the JS implementation -- note ";1" is just a Mozilla convention for versioning APIs. Here's an example: [Constructor(optional long firstNumber), JSImplementation="@mozilla.org/my-number;1"] interface MyNumber { attribute long value; readonly attribute long otherValue; void doNothing(); }; Next, create an
XPCOM component that implements this interface. Basic direct...
... WebIDL attributes are implemented as properties on the JS object or its prototype chain, whereas WebIDL methods are implemented as methods on the object or prototype. ...
...And 8 more matches
Working with windows in chrome code
e window title, which is specified using XUL. The third, and optional, parameter is a list of special window features the window should have. The window.openDialog 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 dialog feature is specified. From
XPCOM components and modules If the Window object is unavailable (for example, when opening a window from
XPCOM component code), you might want to use nsIWindowWatcher interface. Its parameters are similar to window.open; in fact, window.open's implementation calls nsIWindowWatcher's methods. var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Compon...
... .QueryInterface(Components.interfaces.nsIDocShellTreeItem) .rootTreeItem .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindow); This allows you to cross the chrome-content boundaries, and returns the main window object. Finding already opened windows The window mediator
XPCOM component (nsIWindowMediator interface) provides information about existing windows. Two of its methods are often used to obtain information about currently open windows: getMostRecentWindow and getEnumerator. Please refer to the nsIWindowMediator page for more information and examples of using nsIWindowMediator. === Example: Opening a window only if it's not opened already === XXX TBD Passing d...
...ber of arguments to that window. Arguments are simple JavaScript objects, accessible through window.arguments property in the opened window. In this example, we're using window.openDialog to open a progress dialog. We pass in the current status text as well as the maximum and current progress values. Note that using nsIWindowWatcher.openWindow is a bit less trivial . ...
...And 8 more matches
Index of archived content - Archive of obsolete content
frame/utils fs/path io/byte-streams io/file io/text-streams lang/functional lang/type loader/cuddlefish loader/sandbox net/url net/xhr places/bookmarks places/favicon places/history platform/
xpcom preferences/event-target preferences/service remote/child remote/parent stylesheet/style stylesheet/utils system/child_process system/environment system/events system/runtime system/unload system/xul-app tabs/utils ...
...pm) Getting started (cfx) List Open Tabs Listen for Page Load Listening for Load and Unload Localization Logging Modifying Web Pages Based on URL Modifying the Page Hosted by a Tab Open a Web Page Troubleshooting Unit Testing Using
XPCOM without chrome Using third-party modules (jpm) Bootstrapped extensions Code snippets Alerts and Notifications Autocomplete Bookmarks Boxes Canvas code snippets Cookies Customizing the download progress bar ...
... bar Delayed Execution Dialogs and Prompts Downloading Files Drag & Drop Embedding SVG Examples and demos from articles File I/O Finding window handles Forms related code snippets HTML in XUL for rich tooltips HTML to DOM IsDefaultNamespace JS
XPCOM JavaScript Debugger Service JavaScript timers JavaScript Daemons Management Label and description LookupNamespaceURI LookupPrefix Miscellaneous Modules On page load Page Loading Post data to window ...
...And 7 more matches
RefPtr
RefPtr (formerly known as nsRefPtr, see bug 1207245) is a general class to implement reference counting pointers for objects. It is similar to nsCOMPtr, but does not require that the type be an
XPCOM interface. Like with nsCOMPtr, it is the responsibility of the object itself to implement reference counting. This is done using the functions AddRef() and Release(), which respectively modify a variable of type nsAutoRefCnt, which basically is a wrapper around a count of the number of references refering to the class. ...
... nsCOMPtr, it is the responsibility of the object itself to implement reference counting. This is done using the functions AddRef() and Release(), which respectively modify a variable of type nsAutoRefCnt, which basically is a wrapper around a count of the number of references refering to the class. ...
...ons AddRef() and Release(), which respectively modify a variable of type nsAutoRefCnt, which basically is a wrapper around a count of the number of references refering to the class. When should I use nsCOMPtr versus RefPtr? The rules are simple: use nsCOMPtr to hold pointers to
XPCOM interfaces, and use RefPtr to hold pointers to concrete class, even if the concrete class implements one or more
XPCOM interfaces. ...
...And 7 more matches
Creating Event Targets - Archive of obsolete content
ling users of the module to listen for these events using the SDK's standard event API. Using the Places API First, let's write some code using Places API that logs the URIs of bookmarks the user adds. Create a new directory called "bookmarks", navigate to it, and run jpm init, accepting all the defaults. ...
...ents using the SDK's standard event API. Using the Places API First, let's write some code using Places API that logs the URIs of bookmarks the user adds. Create a new directory called "bookmarks", navigate to it, and run jpm init, accepting all the defaults. ...
... Modules as Event Targets We can adapt this code into a separate module that...
...And 6 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
ntent and web applications. Gecko features full support for open Internet standards such as CSS1, HTML 4.0, DOM1, RDF, XML and JavaScript. Modular, Embeddable: Gecko's modular architecture enables developers to add or remove modules with little effort, fitting the software to the available hardware and adjusting functionality to match product requirements. Gecko is implemented as a collection of
XPCOM components that can be easily added or removed. Flexible programming interfaces such as the Web Shell API, the Java wrapper API and the Gecko ActiveX Control make Gecko easily embeddable into applications and devices. Full Browser Functionality: Gecko allows any desktop application as well as new devices, products and appliances to be web-enabled, with complete browser functionality. Supported s...
.../O, a generic disk and memory cache service, asynchronous caching DNS resolution, web proxies, and HTTPS. The following architectural diagram depicts Necko and its interaction with subsystems: Necko is powerful, stable and robust, with current development focused on performance and standards-compliance. It has gone through extensive field testing and revision to maximize web site compatibility.
XPCOM, the Cross Platform Component Object Model The Cross Platform Component Object Model (
XPCOM) is one of the main things that makes the Mozilla application environment an actual framework. It is a development environment that provides the following features for the cross-platform software developer: component management file abstraction object message passing memory management This component ...
...platform software developer: component management file abstraction object message passing memory management This component object model makes virtually all of the functionality of Gecko available as a series of components, or reusable cross-platform libraries, that can be accessed from the browser or scripted from any Mozilla application. ...
...And 6 more matches
How to implement a custom XUL query processor component - Archive of obsolete content
XUL supports templating to create a block of content from a datasource query. The XUL Template Guide has lots of detailed information on using XUL templates. XUL provides template query processors for RDF, XML and SQL (mozStorage). The templating system also supports building custom query processors. Custom query processors are
XPCOM components, must implement the nsIXULTemplateQueryProcessor interface and follow some conventions for when registering the component. In this example, we will create a simple JavaScript
XPCOM component. The component will hold a small array of JavaScript objects as its datasource. In practice, you would use your own custom source of data. Here is an example of what our XUL might look like when using a custom query processor: <?xml version="1.0"?> <?xml...
..."?age"/> <label value="?hair"/> <label value="?eye"/> </row> </template> </rows> </grid> </window> A few things to note. We are not really using the datasources in our sample component, so we set it to a dummy value. An empty string would be ok too. The querytype is important. ...
...alue="?hair"/> <label value="?eye"/> </row> </template> </rows> </grid> </window> A few things to note. We are not really using the datasources in our sample component, so we set it to a dummy value. An empty string would be ok too. The querytype is important. It is used to create an instance of our
XPCOM object. ...
...And 6 more matches
Overview of Mozilla embedding APIs
Introduction The Mozilla Public API consists of a collection of services and components which are accessed via
XPCOM interfaces. Mozilla's
XPCOM layer consists of a component model (called
XPCOM) and the infrastructure necessary to support dynamic registration, instantiation and manipulation of
XPCOM components. At the heart of
XPCOM's implementation is the Service Manager and the Component Manager. Together, these two services provide a centralized point for gaining access to all of the public Mozilla interfaces. The Service Manager exposes all of the available
XPCOM services - each service represents a global object which provides some piece of functionality. The Component Manager allows new instances of registered
XPCOM components to be instantiated. The embedding layer consists of ...
...Much of the Gecko functionality is exposed through a component called the nsWebBrowser. Embedding applications can leverage this component to easily access many of Gecko's features. ...
... instance represents the "client-area" of a typical browser window. The WebBrowser exposes a set of interfaces which allow the embedding application to control activity and respond to changes within this client area. Using these interfaces an embedding application can build up its own user interface around a WebBrowser instance. Public Classes The following utility classes are available from the
XPCOM DLL. They provide some basic functionality which should be leveraged when building new
XPCOM components. nsCOMPtr<interface-type> These are templatized smart pointers which transparently deal with
XPCOM reference counting issues. See the nsCOMPtr User's Manual for more information. nsString There are a collection of string classes which support both unicode and ASCII strings. These classe...
...And 6 more matches
How to implement a custom autocomplete search component
SeaMonkey: 1.1+; GTK builds only). The component uses the autocompletesearchparam attribute or searchParam property to allow the developer to define the default directory otherwise only paths beginning with / or ~/ will be autocompleted. Building your custom autocomplete search components Sometimes, you may want to build your own autocomplete source. ...
...ram property to allow the developer to define the default directory otherwise only paths beginning with / or ~/ will be autocompleted. Building your custom autocomplete search components Sometimes, you may want to build your own autocomplete source. To do so you need the following: Create an
XPCOM component that implements the nsIAutoCompleteSearch interface. ...
...o so you need the following: Create an
XPCOM component that implements the nsIAutoCompleteSearch interface. Make sure the contract ID of your
XPCOM component follows the following form: "@mozilla.org/autocomplete/search;1?name=xxx", where "xxx" is the name of your autocomplete source. Implement the list of matched strings using the nsIAutoCompleteResult interface. The simplest way to make an
XPCOM component is to build an
XPCOM JavaScript Component (this cannot be done with a JavaScript module). How to Build an
XPCOM Component in Javascript will step you through the process. ...
...And 6 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
y Taiga (Gomita) Gomibuchi and was originally published in Japanese for the Firefox Developers Conference Summer 2007. Gomita-san won "Most Useful Upgraded Extension" award in Mozilla's 2006 "Extend Firefox" competition for ScrapBook, and was runner-up in the "Extend Firefox 2" contest for FireGestures. The chapters so far have each focused on technologies in isolation--XUL, JavaScript, CSS, and
XPCOM. In this chapter, we'll discuss how to put them together to actually build an extension. An easier method of building a Firefox/Thunderbird Addon for developers who are well-acquainted with IDEs like Netbeans, Eclipse, etc. is to use Netbeans (IDE from Sun Microsystems) and Foxbeans (Plugin for Netbeans, by TeeSoft). Setting up your development environment In order to develop (and test) exten...
...or the Firefox browser window is as follows: chrome://browser/content/browser.xul Here, the package name is "browser", the file "browser.xul", and the type of the package is "content". Source files represented through chrome URLs run with UniversalXPConnect privileges; even if they haven't been granted "use XPConnect as local file" privileges, as discussed in Chapter 4, they will be able to use
XPCOM functions (Figure 1). Extension/ chrome manifest Chrome/ #registered in the chrome content package #Run with privileges locale package skin package Figure 1: Chrome packages and chrome registration (FIXME: Not really explicit and not a Figure) Cross-package overlays The "overlay" technique introduced in Chapter 3 required the use of the xul-overlay instruction in the XUL docum...
...functional implementation. Open a new window and make sure that all three functions--saving a session, restoring a session, and deleting sessions--all work correctly. Phase 3: Creating a preference panel You don't need to use ini files, registries, or anything like that to give users options they can set through a preference panel. Firefox lets you read and write preference values using handy
XPCOM services and create preference panels with interface widgets. In Phase 3, we'll try this out (Figure 15). FIXME: Figure 15: Finished preference panel Directory structure Figure 16 shows the directory structure we'll be using in Phase 3. Table 5 explains the new files being used. Table 5: Files used in Phase 3 FIXME: Make the table cleaner name purpose ...
...And 5 more matches
The Joy of XUL - Archive of obsolete content
they wish to keep proprietary. The Netscape Public License (NPL) and Mozilla Public License (MPL) require developers who alter original work (source code files that are provided with Mozilla) to release the source code for these changes to their customers. Overlays can be used to add features to Mozilla without contaminating the original open source code with proprietary alterations.
XPCOM/XPConnect
XPCOM and XPConnect are complementary technologies that enable the integration of external libraries with XUL applications.
XPCOM, which stands for Cross Platform Component Object Model, is a framework for writing cross-platform, modular software.
XPCOM components can be written in C, C++, and JavaScript, and they can be used from C, C++, JavaScript, Python, Java, and Perl. ...
...enable the integration of external libraries with XUL applications.
XPCOM, which stands for Cross Platform Component Object Model, is a framework for writing cross-platform, modular software.
XPCOM components can be written in C, C++, and JavaScript, and they can be used from C, C++, JavaScript, Python, Java, and Perl. XPConnect is a technology which enables simple interoperation between
XPCOM and JavaScript. XPConnect allows JavaScript objects to transparently access and manipulate
XPCOM objects. It also enables JavaScript objects to present
XPCOM compliant interfaces to be called by
XPCOM objects. ...
...C, C++, and JavaScript, and they can be used from C, C++, JavaScript, Python, Java, and Perl. XPConnect is a technology which enables simple interoperation between
XPCOM and JavaScript. XPConnect allows JavaScript objects to transparently access and manipulate
XPCOM objects. It also enables JavaScript objects to present
XPCOM compliant interfaces to be called by
XPCOM objects. Together,
XPCOM and XPConnect enable developers to create XUL applications that require the raw processing power of compiled languages (C/C++) or access to the underlying operating system. XPInstall XPInstall, Mozilla's Cross Platform Install facility, provides a standard way of packaging XUL application components with an install script that Mozilla can download and execute. XPInstall enable...
...And 5 more matches
BloatView
BloatView is a tool that shows information about cumulative memory usage and leaks. If it finds leaks, you can use refcount tracing and balancing to discover the root cause. How to build with BloatView Build with --enable-debug or --enable-logrefcnt. How to run with BloatView The are two environment variables that can be used.
XPCOM_MEM_BLOAT_LOG If set, this causes a bloat log to be printed on program exit, and each time nsTraceRefcnt::DumpStatistics is called. This log contains data on leaks and bloat (a.k.a. usage).
XPCOM_MEM_LEAK_LOG This is similar to
XPCOM_MEM_BLOAT_LOG, but restricts the log to only show data on leaks. You can set these environment variables to any of the following values. 1 - log to stdout. 2 - log to stderr. filename - write log to a f...
...ffenders. (Should be zero!) Objects Total - The total count of objects allocated of a given class. Objects Rem - The number of objects allocated of a given class that weren't deleted. (Should be zero!) Interesting things to look for: Are your classes in the list? - Look! If they aren't, then you're not using the NS_IMPL_ADDREF and NS_IMPL_RELEASE (or NS_IMPL_ISUPPORTS which calls them) for
xpcom objects, or MOZ_COUNT_CTOR and MOZ_COUNT_DTOR for non-
xpcom objects. Not having your classes in the list is not ok. That means no one is looking at them, and we won't be able to tell if someone introduces a leak. (See below for how to fix this.) The Bytes Leaked for your classes should be zero! - Need I say more? If it isn't, you should use the other tools to fix it. The number of objects remai...
...nfinite" amount of leakage. This happens when something that didn't leak before is now leaking. BloatView and continuous integration BloatView runs on debug builds for many of the test suites Mozilla has running under continuous integration. If a new leak occurs, it will trigger a test job failure. BloatView's output file can also show you where the leaked objects are allocated. ...
...And 5 more matches
Preface
Next >> This is a book about Gecko, and about creating
XPCOM components for Gecko-based applications. Though the emphasis is on the practical steps you take to make your C++ code into a component that can be used in Gecko, we hope that these steps will also give us an occasion to discuss all of the tools, techniques, and technologies that make up
XPCOM. Accordingly, the book is arranged so that you can follow along and create your own components or learn about different
XPCOM topics individually, as in a reference work. ...
...is arranged so that you can follow along and create your own components or learn about different
XPCOM topics individually, as in a reference work. For example, the introduction includes a discussion of components and what they are, and the first chapter - in which you compile the basic code and register it with Mozilla - prompts a discussion of the relationship between components and modules, of
XPCOM interfaces, and of the registration process in general. The top of each chapter provides a list of the major topics covered. Sidebar sections are included to highlight technical details. By the end of the book, if we've done our job, you will have learned how to build a component and you will know something about the framework for these components in Gecko, which is
XPCOM. Who Should Read This ...
...al details. By the end of the book, if we've done our job, you will have learned how to build a component and you will know something about the framework for these components in Gecko, which is
XPCOM. Who Should Read This Book No one. It is badly out of date, and much of what it says is either no longer remotely accurate, or is severely deprecated. If you are a historian, though... Creating
XPCOM Components is meant for C++ developers. Though you can create
XPCOM components in JavaScript and other languages, and though you might be able to follow along as a C programmer, the component implementation code is written in C++, and much of the discussion of how to make your codeinto an
XPCOM component starts from C++. You don't need to be a C++ expert, however. Although basic ideas such as inh...
...And 5 more matches
xptcall FAQ
Both of these facilities are required by XPConnect. These facilities are also used by
xpcom/proxy. It may also be used by other subsystems in the future. ...
... Both of these facilities are required by XPConnect. These facilities are also used by
xpcom/proxy. It may also be used by other subsystems in the future. ...
...library. It is implemented using platform specific C/C++ and assembly language code. It is used to facilitate cross language and cross thread method calls. Porting this code is required in order to make Mozilla run on any given platform. Why does xptcall exist? xptcall exists for two reasons: To support invoking arbitrary methods on
XPCOM interfaces. To support dynamically impersonating any
XPCOM interface. Both of these facilities are required by XPConnect. These facilities are also used by
xpcom/proxy. It may also be used by other subsystems in the future. The xptcall approach was chosen over an approach that would have required generating stub code for calling and implementing all interfaces. Though the chosen approach requires some core platform specific code, it has minimal footpr...
...And 5 more matches
XUL Migration Guide - Archive of obsolete content
is a good candidate for migration via a comparison of the benefits and limitations of the SDK versus XUL development. Next, we'll look at some of the main tasks involved in migrating: working with content scripts using the SDK's supported APIs how to go beyond the supported APIs when necessary, by: using third party modules using the SDK's low-level APIs getting direct access to
XPCOM Finally, we'll walk through a simple example. Should You Migrate? See this comparison of the benefits and limitations of SDK development and XUL development. Whether you should migrate a particular add-on is largely a matter of how well the SDK's supported APIs meet its needs. If your add-on can accomplish everything it needs using only the supported APIs, it's a good candidate ...
...e benefits and limitations of SDK development and XUL development. Whether you should migrate a particular add-on is largely a matter of how well the SDK's supported APIs meet its needs. If your add-on can accomplish everything it needs using only the supported APIs, it's a good candidate for migration. If your add-on needs a lot of help from third party packages, low-level APIs, or
XPCOM, then the cost of migrating is high, and may not be worth it at this point. If your add-on only needs a little help from those techniques, and can accomplish most of what it needs using the supported APIs, then it might still be worth migrating: we'll add more supported APIs in future releases to meet important use cases. User Interface Components XUL-based add-ons typically implement ...
...rectory there called "chrome". In that directory you can keep your "content", "locale", and "skin" subdirectories: This allows you to refer to objects in these directories from "chrome.manifest" using a relative path, like "chrome/content". This is provided only as a migration aid, and it's still a good idea to port XUL windows to HTML. Content Scripts In a XUL-based add-on, code that uses
XPCOM objects, code that manipulates the browser chrome, and code that interacts with web pages all runs in the same context. But the SDK makes a distinction between: add-on scripts, which can use the SDK APIs, but are not able to interact with web pages content scripts, which can access web pages, but do not have access to the SDK's APIs Content scripts and add-on scripts communicate by sending ...
...And 4 more matches
Finishing the Component
When the component starts up, it populates a list of URLs read in from a file stored next to the Gecko binary on the local system. Using Frozen Interfaces The core functionality of blocking sites is still missing, however. ...
... are not ready to be published. This puts you in the same situation as many developers using Mozilla - you want to use some specific functionality, but the interfaces seem to change on a daily basis. All of the Mozilla source code is publicly available, and interfaces can be used easily enough. Grab the right headers, use the Component or Service Manager to access the interface you want, and the
XPCOM object(s) that implement that interface will do your bidding. With this huge amount of flexibility, however, you lose compatibility. If you use "stuff" that isn't frozen, that stuff is subject to change in future versions of Gecko. If you want to be protected against changes in Gecko, you must only use interfaces and APIs that are clearly marked as FROZEN. The marking is made in the comments abo...
...te a header from this IDL file using the xpidl compiler. Once you have these interface and header files, you can modify the WebLock class to implement the nsIContentPolicy interface. The Weblock class will then support four interfaces: nsISupports, nsIObserver, nsIContentPolicy, and iWeblock. WebLock Interfaces Interface Name Defined by Status Summary nsISupports
XPCOM Frozen Provides interface discovery, and object reference counting nsIObserver
XPCOM Frozen Allows messaging passing between objects nsIContentPolicy Content Not Frozen Interface for policy control mechanism iWeblock Web Lock Not Frozen Enables and disables Weblock. Also, provides access to the URL that are whitelisted. Implementi...
...And 4 more matches
nsIDOMEvent
Inherits from: nsISupports Last changed in Gecko 16.0 (Firefox 16.0 / Thunderbird 16.0 / SeaMonkey 2.13) Note: As of Gecko 16.0, the nsIPrivateDOMEvent interface was merged into this interface. Everything marked as Gecko 16.0 was previously available in that interface. See bug 761613. ...
...sIPrivateDOMEvent interface was merged into this interface. Everything marked as Gecko 16.0 was previously available in that interface. See bug 761613. ...
...iolates the
XPCOM interface guidelines void duplicatePrivateData(); Native code only! nsEventPtr GetInternalNSEvent(); Violates the
XPCOM interface guidelines boolean getPreventDefault(); Deprecated since Gecko 16.0 void initEvent(in DOMString eventTypeArg, in boolean canBubbleArg, in boolean cancelableArg); boolean IsDispatchStopped(); Violates the
XPCOM interface guidelines void preventBubble(); Obsolete since Gecko 24 void preventCapture(); Obsolete since Gecko 24 void preventDefault(); void Serialize(in IPCMessagePtr aMsg, in boolean aSerializeInterfaceType); Violates the
XPCOM interface guidelines void setTarget(in nsIDOMEventTarget aTarget); Native code only! void SetTrusted(in boolean...
...And 4 more matches
getFile
If true, this lets the Directory Service cache results to improve the performance of directory lookups. ...
...given standard path location. The individual platform implementation of nsIDirectoryServiceProvider maps the symbolic path location passed to this function and returns the appropriate nsIFile. nsIFile getFile( in string aName, out boolean aPersistent ); Parameters aName [in] The symbolic name for a file or directory location. See Symbolic names below for a list of accepted values.
XPCOM File System Aliases aPersistent [out] This output parameter indicates to the caller whether or not the returned location is persistent. If true, this lets the Directory Service cache results to improve the performance of directory lookups. If false, then the Directory Service will not cache the results of this method. Symbolic names The list of symbolic names is subject to change, so be...
...ersistent [out] This output parameter indicates to the caller whether or not the returned location is persistent. If true, this lets the Directory Service cache results to improve the performance of directory lookups. If false, then the Directory Service will not cache the results of this method. Symbolic names The list of symbolic names is subject to change, so be sure to take a look at the
xpcom/io/nsDirectoryServiceDefs.h file for the version of Gecko you're working with for the latest list. Available on all platforms These symbolic names are available on all platforms (although, of course, they may refer to different physical paths on the storage device). C constant String value Notes NS_OS_HOME_DIR "Home" NS_OS_TEMP_DIR "TmpD" ...
...And 4 more matches
nsISupports proxies
This technology has been removed in Firefox 12 because it was very complex and often lead to strange deadlock conditions. ...
...This technology has been removed in Firefox 12 because it was very complex and often lead to strange deadlock conditions. ...
...This technology has been removed in Firefox 12 because it was very complex and often lead to strange deadlock conditions. ...
...And 4 more matches
Miscellaneous - Archive of obsolete content
s to a XULRunner application You need to ship a XULRunner application with your own SSL certificates? For Firefox, you could use the Client Customization Kit (CCK) to create an extension that does exactly that. To get the same feature for your XULRunner application, follow those steps: First, put the certificates you want to ship into the content/certs folder of your application. ...
...se steps: First, put the certificates you want to ship into the content/certs folder of your application. Then create a
XPCOM service that adds the certificates inside that directory to the certs database on application startup. ...
...MUtils.jsm"); const gObserver = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService); const gIOService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); function CertsService() {} CertsService.prototype = { observe: function(aSubject, aTopic, aData) { switch(aTopic) { case "app-startup": gObserver.addObserver(this,"
xpcom-shutdown",false); gObserver.addObserver(this,"final-ui-startup",false); break; case "
xpcom-shutdown": gObserver.removeObserver(this,"final-ui-startup"); gObserver.removeObserver(this,"
xpcom-shutdown"); break; case "final-ui-startup": this.init(); break; }...
...And 3 more matches
JavaScript Object Management - Archive of obsolete content
espace is declared using var. We need the namespace to be a global object that it can be used everywhere in the window chrome. You can include functions in any namespace, since namespaces are just regular JS objects. That should come in handy when you have general utility functions or properties that you want to use across all objects within the namespace. For instance, there are frequently used
XPCOM services such as the Observer service that can be included as members in the namespace: /** * <Namespace> namespace. */ if (typeof <Namespace> == "undefined") { var <Namespace> = { /** * Initializes this object. */ init : function() { this.obsService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); } }; <Namespace>.init(); ...
...arameter. In this case we set the delay to 0, which means the function should be executed as soon as possible. Firefox has a minimum delay of 10-15ms (taken from this blog post), so it won't really run instantly. It is more than enough to let the window finish its load. Use window.setTimeout and window.setInterval to control timed code execution. In case you're using JavaScript Code Modules or
XPCOM objects, where a window object is not readily available, use an nsITimer instead. This post suggests a way to achieve a true zero ms timeout, as a simple way to achieve parallelism in JS code. Notice the way we send callback functions as parameters, and the use of an alternate reference for this which we always name that. This is all necessary due to a JavaScript feature (quirk would be a be...
... windows open; never assume everything will work the same as with a single window. Now, in most cases you'll need to coordinate data in a way that it is consistent for all open Firefox windows. There are several ways in which you can do this. Preferences is one of them, and they are covered in another section of this tutorial. Two other ways are JavaScript Code Modules (Firefox 3 and above), and
XPCOM. JavaScript Code Modules JavaScript Code Modules (also known as JSM) are new to Firefox 3, and they're the best tool for keeping everything in sync between windows. They're very simple to set up. The first thing you need to do is add an entry in the chrome.manifest file: resource xulschoolhello modules/ Javascript code modules are accessed with the resource protocol, which is very s...
...And 3 more matches
Index - Archive of obsolete content
How to implement a custom XUL query processor component XUL supports templating to create a block of content from a datasource query. The XUL Template Guide has lots of detailed information on using XUL templates. XUL provides template query processors for RDF, XML and SQL (mozStorage). The templating system also supports building custom query processors. ...
...ystem also supports building custom query processors. Custom query processors are
XPCOM components, must implement the nsIXULTemplateQueryProcessor interface and follow some conventions for when registering the component. 436 Index Found 1218 pages: 437 International characters in XUL JavaScript Firefox, Gecko, Guide, Internationalization, JavaScript, Mozilla,
XPCOM, XUL Gecko 1.8, as used in Firefox 1.5 and other applications, added support for non-ASCII characters in JavaScript files loaded from XUL files. 438 Introduction to XUL Guide, XUL Mozilla has configurable, downloadable chrome, meaning that the arrangement and even presence or absence of controls in the main window is not hardwired into the application, but loaded from a...
... 596 Other Resources XUL No summary! 597 Popup Guide XUL, XUL Popup Guide No summary! 598 ContextMenus XUL, XUL Popup Guide A context menu is a menu where the items on the menu are specific to the context in which the menu was opened. A typical usage is for the user to right-click on an element to display a menu of commands ...
...And 3 more matches
Common causes of memory leaks in extensions - Extensions
this idea: If the user disables JavaScript globally or locally (such as by using an add-on like NoScript), then using the content window functions won't work. Problems in bootstrapped (restartless) add-ons Bootstrapped extensions use a bootstrap.js compartment. If you put a reference to anything within this compartment into a long-lived window object (such as browser.xul), JavaScript module or
XPCOM component, the bootstrap.js compartment will become a zombie. For example, the following code snippets -- part of a bootstrap.js -- will leak: function leakref() {} function modifyDocument(document) { var a = document.createElement("a"); document.body.appendChild(a); // The new DOM node holding a reference to leakref will prevent // that function object from being garbage collected and...
...y use an unload event listener: addEventListener("unload", function() { Services.obs.removeObserver(myObserver, "private-browsing"); }, false); In bootstrap.js (restartless add-ons) unregister your observer in your shutdown function: function shutdown() { // ... ...
...add-ons) unregister your observer in your shutdown function: function shutdown() { // ... ...
...And 3 more matches
Mozilla DOM Hacking Guide
Mozilla gives you the opportunity not only to use very powerful and complete DOM support, but also to work on a world-class implementation of one of the greatest Internet technologies ever created. Mozilla's DOM is coded almost entirely in C++. Seriously hacking on it requires excellent knowledge of C++ and
XPCOM, Mozilla's own component model. In this document I will try to outline the main aspects of the implementation, beginning with the Class Info mechanism, which lies at the heart of the DOM, then with the description of various interfaces and classes. Since I am myself still learning how it works, don't expect this to be a complete reference quite yet. If you can contribute any time or knowledge to this document, it is greatly appreciated! Target audience: People interested in l...
...hanism, which lies at the heart of the DOM, then with the description of various interfaces and classes. Since I am myself still learning how it works, don't expect this to be a complete reference quite yet. If you can contribute any time or knowledge to this document, it is greatly appreciated! Target audience: People interested in learning how the DOM is implemented. Prior knowledge of C++ and
XPCOM is assumed. If you don't know
XPCOM yet, and would like to be able to read this document quickly, you can read the Introduction to
XPCOM for the DOM. Otherwise, for more detailed
XPCOM documentation, please see the
XPCOM project page. Class Info and Helper Classes Introduction to Class Info Class Info is what gives the DOM classes their correct behavior when used through XPConnect. It lies at ...
...r method that was not previously resolved. Please see the nsIXPCScriptable interface for more information. The nsDOMClassInfo class The heart of Class Info is the nsDOMClassInfo class, defined in nsDOMClassInfo.h. It implements two interfaces besides nsISupports: nsIXPCScriptable and nsIClassInfo. We already know what nsIXPCScriptable is used for (see the previous Section). nsIClassInfo is an
XPCOM interface, very well described by Mike Shaver in this overview of nsIClassInfo. Basically it contains convenient methods to find out about the interfaces an object promises to support. In our case, this list of interfaces will be populated by "Class Info". See also Section 1.5 on the Init() function and Section 1.2 on interface flattening. We saw in Section 1.3 that nsDOMClassInfo is the base cl...
...And 3 more matches
Observer Notifications
he observer service for the profile-after-change notification. See Receiving startup notifications for more information about how this works. Starting in Firefox 3.5 components can simply register for the profile-after-change notification in nsICategoryManager. Topic Description * Everything. [nsObserverService.cpp] Topic Description
xpcom-startup Note: An extension can no longer be registered to receive this notification in Firefox 4 and later. See
XPCOM changes in Gecko 2.0 for details. Called when
xpcom is initialized. Many things are not available for use at this point. To receive this notification you have to register with nsICategoryManager. The registered component is always retrieved as a singleton (That is get...
...com is initialized. Many things are not available for use at this point. To receive this notification you have to register with nsICategoryManager. The registered component is always retrieved as a singleton (That is getService() will be used to instantiate it). app-startup Note: An extension can no longer be registered to receive this notification in Firefox 4 and later. See
XPCOM changes in Gecko 2.0 for details. General event for application startup. To receive this notification you have to register with nsICategoryManager. Prepend "service," to the contract ID in the category registration to be invoked via getService() instead of createInstance(). profile-do-change This is fired after the profile has been selected. You will not be able to access use...
...rences, bookmarks, or anything that uses the profile folder until this event occurs. This occurs after any profile migration. profile-after-change This is fired after all the observers for profile-do-change have been notified. You can register with nsICategoryManager to receive this notification. Prior to Firefox 3.5, this was available to observers observing the app-startup/
xpcom-startup notification. final-ui-startup Triggered just before the first window for the application is displayed. sessionstore-windows-restored Sent by the session restore process to indicate that all initial browser windows have opened. Note that while the window are open and the chrome loaded the tabs in the windows may still be being restored after this ...
...And 3 more matches
imgIContainer
void getFrameColormap(in unsigned long framenumber, [array, size_is(paletteLength)] out PRUint32 paletteData, out unsigned long paletteLength); Obsolete since Gecko 2.0 unsigned long getFrameImageDataLength(in unsigned long framenumber); Obsolete since Gecko 2.0 ImageContainer getImageContainer(); Native code only! ...
...ize_is(paletteLength)] out PRUint32 paletteData, out unsigned long paletteLength); Obsolete since Gecko 2.0 unsigned long getFrameImageDataLength(in unsigned long framenumber); Obsolete since Gecko 2.0 ImageContainer getImageContainer(); Native code only! ...
... Obsolete since Gecko 2.0 void setDiscardable(in string aMimeType); Native code only! ...
...And 3 more matches
mozIRegistry
tinct from your source code. And it happens that we've chosen, up till now, to store that information in the "Netscape registry" file. Which explains how this information came to be associated with the notion of a "registry." Someday (I hope) this page will be properly titled so that everybody knows it is the place to come to in order to find out how they are supposed to link together the various
XPCOM components that together form the Mozilla browser. The information below is intended to tell you everything you need to know about how to do that. Summary Clients will rely on nsRepository to create instances of a given class. Clients requiring dynamic "binding" of CLSIDs will be required to use some higher-level services (TBD) to figure out the CLSIDs they should use. The intent is that such ...
...you need to know about how to do that. Summary Clients will rely on nsRepository to create instances of a given class. Clients requiring dynamic "binding" of CLSIDs will be required to use some higher-level services (TBD) to figure out the CLSIDs they should use. The intent is that such services themselves be built on top of the new mozIRegistry interface. We are proposing a new "mozIRegistry"
XPCOM interface that provides the same level of function as is currently provided by the "netscape registry" implemented in libreg. nsRepository will be modified to use this interface, thereby enabling alternative registry implementations to be substituted at run/link time. There will be two registry interface implementations: one based solely on libreg (for "compatibility") and a fancier RDF-based one...
...her add the information about it or at least put in a link to it's documentation. Higher-Level Application Components This box represents all the potential user's of the core registry/repository interfaces. Your code (most likely) falls in this box. These components will, to various degrees, need to use other components to do their thing. Those other components presumably implement particular
XPCOM interfaces. So how do you go about creating an object that can provide the interface your component requires? One way is to create instances by using nsRepository. nsRepository is essentially a mapping from
XPCOM CLSIDs to class factories, plus code to manage that mapping, including functions that create instances of a given CLSID. The nsRepository functions are declared in nsRepository.h. Much m...
...And 3 more matches
nsIContentViewer
2.7) Implemented by: ?????????????????????????????????????. ...
...rg/????????????????????????????"] .createInstance(Components.interfaces.nsIContentViewer); Method overview void clearHistoryEntry(); void close(in nsISHEntry historyEntry); void destroy(); [noscript,not
xpcom,nostdcall] nsIViewPtr findContainerView(); void getBounds(in nsIntRectRef aBounds); Native code only! [noscript,not
xpcom] nsIDocumentPtr getDocument(); void hide(); void init(in nsIWidgetPtr aParentWidget, [const] in nsIntRectRef aBounds); Native code only! void loadComplete(in unsigned long aStatus); void loadStart(in nsISupports aDoc); void move(in long aX, in long aY); void open(in nsISupports aState, in nsISHEntry aSHEntry); void pageHide(in boole...
...oid pageHide(in boolean isUnload); boolean permitUnload([optional] in boolean aCallerClosesWindow); boolean requestWindowClose(); void resetCloseWindow(); void setBounds([const] in nsIntRectRef aBounds); Native code only! void setDocumentInternal(in nsIDocumentPtr aDocument, in boolean aForceReuseInnerWindow); Native code only! ...
...And 3 more matches
nsISHEntry
long index); void clearChildShells(); nsISHEntry clone(); void create(in nsIURI URI, in AString title, in nsIInputStream inputStream, in nsILayoutHistoryState layoutHistoryState, in nsISupports cacheKey, in ACString contentType, in nsISupports owner, in unsigned long long docshellID, in boolean dynamicCreation); Native code only! ...
...wner, in unsigned long long docshellID, in boolean dynamicCreation); Native code only! nsDocShellEditorDataPtr forgetEditorData(); Violates the
XPCOM interface guidelines nsIContentViewer getAnyContentViewer(out nsISHEntry ownerEntry); void getScrollPosition(out long x, out long y); void getViewerBounds(in nsIntRect bounds); Native code only! ...
...nes nsIContentViewer getAnyContentViewer(out nsISHEntry ownerEntry); void getScrollPosition(out long x, out long y); void getViewerBounds(in nsIntRect bounds); Native code only! boolean hasDetachedEditor(); Violates the
XPCOM interface guidelines boolean hasDynamicallyAddedChild(); boolean isDynamicallyAdded(); void setEditorData(in nsDocShellEditorDataPtr aData); Violates the
XPCOM interface guidelines void setIsSubFrame(in boolean aFlag); void setScrollPosition(in long x, in long y); void setTitle(in AString aTitle); void setUniqueDocIdentifier(); void setURI(in nsIURI aURI); void setViewerBounds(in nsIntRect bounds); Native code only! void syncPresentationState(); Attributes Attribute Type Description cacheKey nsISupports Set and get the cache ke...
...And 3 more matches
nsIServiceManager
The service manager depends on the repository to find and instantiate factories to obtain services. ...
...Unlike createInstance, this will always return the same object each time it is called with the same arguments. void getService( in nsCIDRef aClass, in nsIIDRef aIID, [iid_is(aIID),retval] out nsQIResult result ); Parameters aClass The ClassID of the service that is being requested. aIID The interface type to be returned. result The result...
...IID, [iid_is(aIID),retval] out nsQIResult result ); Parameters aClass The ClassID of the service that is being requested. aIID The interface type to be returned. result The resulting interface pointer. Exceptions thrown NS_ERROR_FACTORY_NOT_REGISTERED Indicates that the specified class is not registered. getServiceByContractID() This method returns a reference to a particular
XPCOM service given the ContractID of the service. void getServiceByContractID( in string aContractID, in nsIIDRef aIID, [iid_is(aIID),retval] out nsQIResult result ); Parameters aContractID The ContractID of the service that is being requested. aIID The interface type to be returned. result The resulting interface pointer. Exceptions thrown NS_ERROR_FACTORY_NOT_REGISTERED Indica...
...And 3 more matches
Using the Gecko SDK
A frozen Gecko API is one that is included in the Gecko and marked frozen with the text <tt>@status FROZEN</tt> (with NSPR as the exception to the rule). ...
...A frozen Gecko API is one that is included in the Gecko and marked frozen with the text <tt>@status FROZEN</tt> (with NSPR as the exception to the rule). ...
...A frozen Gecko API is one that is included in the Gecko and marked frozen with the text <tt>@status FROZEN</tt> (with NSPR as the exception to the rule). ...
...And 3 more matches
XPIDL
Interface Description Languages (IDL) are used to describe interfaces in a language- and machine-independent way. IDLs make it possible to define interfaces which can then be processed by tools to autogenerate language-dependent interface specifications. XPIDL is expected to converge towards WebIDL in the future. Note: Starting in Gecko 9.0, the older xpidl utility, which was previously used to generate C++ header files, typelib information, and so forth has been replaced with pyxpidl in the Gecko SDK. pyxpidl has been used for some time now, but now the older tool has been fully retired. ...
...he older xpidl utility, which was previously used to generate C++ header files, typelib information, and so forth has been replaced with pyxpidl in the Gecko SDK. pyxpidl has been used for some time now, but now the older tool has been fully retired. Writing XPIDL interface files XPIDL closely resembles OMG IDL, with extended syntax to handle IIDs and additional types. Some examples are in the
xpcom/base and
xpcom/ds directories of the Mozilla tree. XPIDL:Syntax (Now up to date again) XPIDL syntax (Out of date) XPIDL Author's Guide (Not as out of date) Explanation of IDL semantics A full guide to the syntax can be found at XPIDL:Syntax, which is written in an ABNF form. An xpidl file is essentially just a series of declarations. At the top level, we can define typedefs, native types...
... parameters. When called from a JavaScript context, they invocation looks as it is declared for the most part; some parameter properties can adjust what the code looks like. The calls are more mangled in native contexts. An important attribute for methods and attributes is scriptability. A method or attribute is scriptable if it is declared in a scriptable interface and it lacks a noscript or not
xpcom property. Any method that is not scriptable can only be accessed by native code. However, scriptable methods must contain parameters and a return type that can be translated to script: any native type, save those declared with an nsid, utf8string, cstring, astring, or jsval property, may not be used in a scriptable method or attribute. An exception to the above rule is if the parameter has the ii...
...And 3 more matches
Using Dependent Libraries In Extension Components - Archive of obsolete content
ension-directory/components/interface2.xpt extension-directory/components/bsmedberg_stub.dll extensions/stub/Makefile.in # Copyright (c) 2005 Benjamin Smedberg <benjamin@smedbergs.us> DEPTH = ../.. ...
...stub/Makefile.in # Copyright (c) 2005 Benjamin Smedberg <benjamin@smedbergs.us> DEPTH = ../.. ...
...) 2005 Benjamin Smedberg <benjamin@smedbergs.us> DEPTH = ../.. ...
...And 2 more matches
Source code directories overview - Archive of obsolete content
e level things instead of build level things (which are a stored in the build directory). content was split off from layout and contains objects as they are exposed to the DOM. db contains C code for the mdb/Mork database which is a low-level, general-purpose and cross-platform file library. It is used to store mail box data, news data and global history data. It has not been updated to support
XPCOM yet. This code originated in the Mozilla Classic code base. dbm contains C code for managing, reading and writing hash tables. It is used for the auto-completion feature on the URL edit box (stored in netscape.hst in Mozilla Classic) and for the cached pages index (stored in fat.db in Mozilla Classic). This code originated at UC Berkeley. directory contains the LDAP SDK. docshell contains C in...
... Sun JVM (Java Virtual Machine). It does not include the code for the virtual machine itself, though. themes contains the default themes for Mozilla, modern and classic. toolkit contains the code for the toolkit used for Firefox, Thunderbird and other standalone applications. This will be covered below. tools contains C code for the Linux-only Leaky tool. Leaky can help detect memory leaks and
XPCOM reference counting problems. uriloader contains C interfaces and code for invoking the correct viewer for the content contained at a certain URL. For example, if this code determines that the content is a mail message, it looks up the appropriate listener (probably Netscape Messenger) and passes the mail message to it for display. It is generic and can hand the content off to internal components...
...late the individual content that it contains. For example, a scrolling view will find out the scroll bar positions and tell its content where to draw according the scroll bar thumbs. webshell contains C interfaces, C code, Linux shell scripts and other files for embedding Mozilla in other programs on various different platforms in various different ways (e.g. ...
...And 2 more matches
GRE - Archive of obsolete content
lla suite never supported a GRE on Mac. XULRunner: the new GRE XULRunner is the new version of the GRE, which not only allows embedding but is capable of bootstrapping entire XUL applications such as Firefox. XULRunner supports or is planned to support embedding on all three major platforms (Windows, Mac, and Linux). Finding and using a GRE from application code Avoid linking directly against
xpcom.dll If an application wishes to use the GRE, it must take careful steps to ensure that it links against the proper libraries. If you link directly against
xpcom.dll/lib
xpcom.so (
xpcom.lib import lib), your application will not launch unless
xpcom.dll is in your PATH. This prevents dynamically finding a compatible GRE at runtime. Find a compatible GRE Note: Support for locating a standalone gl...
...f you link directly against
xpcom.dll/lib
xpcom.so (
xpcom.lib import lib), your application will not launch unless
xpcom.dll is in your PATH. This prevents dynamically finding a compatible GRE at runtime. Find a compatible GRE Note: Support for locating a standalone glue was removed in Gecko 6.0. To find a compatible GRE, you should use the function GRE_GetGREPathWithProperties() (declared in
xpcom/glue/standalone/ns
XPCOMGlue.h). This allows the embedder to specify what version(s) of GRE are appropriate, and to specify any special features the GRE must have (currently there are no special features defined). Statically link to
xpcomglue.lib (the "standalone glue") The solution is to statically link against
xpcomglue.lib, also known as the "standalone glue" (see
XPCOM Glue). This library pr...
... to specify what version(s) of GRE are appropriate, and to specify any special features the GRE must have (currently there are no special features defined). Statically link to
xpcomglue.lib (the "standalone glue") The solution is to statically link against
xpcomglue.lib, also known as the "standalone glue" (see
XPCOM Glue). This library provides a layer of indirection between embedding code and
XPCOM. To use the
XPCOM glue, you must follow these steps: Compile your code with
XPCOM_GLUE defined. Link with
xpcomglue.lib (not
xpcomglue_s.lib!). Don't link against the NSPR libs. Find a compatible GRE (see above). Dynamically link to that GRE using the
XPCOMGlueStartup() function. See environment variables below. Initialize
XPCOM and do your work; when finished, shut down
XPCOM. Unlink XPC...
...And 2 more matches
RDF Datasource How-To - Archive of obsolete content
This document is a cookbook that describes how to create a native, client-side datasource that works with Mozilla's RDF implementation. It supersedes (and borrows from) the original document put together by Robert Churchill. What is a datasource? The "RDF universe" consists of a set of statements about Internet resources; for example, "my home page was last modified April 2nd", or "that news article was sent by Bob". ...
.... For examples of an implementation like this, look at the RDF/XML datasource or the bookmarks datasource. You may want to choose this implementation if your primary goal is to "wrap" a legacy data store. This implementation may cause problems if your data store can be modified "on the fly" by other agents. Aggregate the in-memory datasource. This is an extreme case of delegation, where you use
XPCOM aggregation to implement the nsIRDFDataSource interface. See Aggregating the In-Memory Datasource for technical details. If you take this approach, you won't be able to selectively implement methods of the nsIRDFDataSource interface; instead, all of the methods will be "forwarded" to the in-memory datasource. This can be useful if your datasource is "read-only", and you aren't worried about modif...
... some outside agent (e.g., new mail arriving). You may also need to choose this implementation if the data set which your datasource is modeling is too large to fit in to memory (e.g., the entire file system structure). [More info on what each method needs to do here] RDF Commands [Describe what commands are, and why you'd implement them.] Registering the datasource component A datasource is an
XPCOM component. As such, it must (currently, see [1]) have: An
XPCOM CLSID to identify the data source implementation An implementation class (that corresponds to the CLSID) whose code lives in a DLL. The DLL must be located in the
XPCOM components directory A factory that is registered to an
XPCOM ProgID in order to be instantiated from the repository. Constructing a DLL for a component is beyond t...
...And 2 more matches
XPJS Components Proposal - Archive of obsolete content
This is a proposal for a system that got implemented, but it may differ from the actual implementation. See the status document for more recent info on the status of this proposal. Draft 1.0 What are XPJS Components? XPJS Components is a (cheesy) name for a system to support
xpcom components written in JavaScript. Now, you might ask: "Isn't that what XPConnect does?" And I would answer that XPConnect is necessary, but not sufficient to the task. XPConnect provides the mechanisms for communication between native and JS
xpcom components, but it does not provide all of the infrastructure to register and instantiate JS components outside of the limitations of the browser window. XPJS will provide that infrastructure. So what does this mean? The XPJS Component system will support impl...
...It will support service and factory registration. These components will be independent of web content and browser windows. They will run from the user's disk just like native components. ...
... expected to have the functions: NSRegisterSelf NSGetFactory NSUnregisterSelf (optional) NSCanUnload (optional) Each .js file might implement one or more components. We will have one native module - called the XPJSManager - which holds this system together. The XPJSManager is in charge of loading these .js files, helping them register themselves, and acting as an intermediary between the
xpcom component manager and the JS code. XJS Components are not run in browser windows. Each .js file (let's call it a module) is started up and run in the context of a relatively 'raw' JS global object. The standard (non-DOM) JS classes will be available. The xpconnectComponents object will be available. And some additional yet to be defined objects may be available. The xpconnectComponents object al...
...And 2 more matches
A XUL Bestiary - Archive of obsolete content
ted in the Application Object Model in the hierarchy of XUL widgets: browser, menu, menuitem, and so on. The DOM and the AOM form a kind of continuum, the whole of which is manipulable from the standards upon which XUL is based. Near Synonyms for XUL There is much confusion about the words that begin with "X" in the Mozilla Open Source Project. The Mozilla XPArchitecture section below describes
XPCOM, XPIDL, and XPConnect, three somewhat related technologies for getting access to application code from the interface. This section describes XUL, XPToolkit, and XPFE, which are in some respects synonymous and in others quite different. In briefest terms, XUL is the XML-based language used for creating interfaces, XPToolkit is the set of XUL widgets (menus, toolbar, etc.) actually assembed for th...
...s like socket interfaces, editing, mail/news, security. The technologies that make this possible are perhaps the least understood of the phalanx of innovations that is Mozilla. In addition to the small matter of programming these serious things in C++ and compiling them platform for platform, the architects and developers of Mozilla use three "XP" technologies to link the core with the interface. ...
...mall matter of programming these serious things in C++ and compiling them platform for platform, the architects and developers of Mozilla use three "XP" technologies to link the core with the interface.
XPCOM is not a programming language but an approach to programming (in C++, say) that provides for a truly cross-platform Component Object Model, whence the technology gets its name. Based on COM,
XPCOM insists that chunks of code provide language- and platform-neutral interfaces that other objects can use to access its services. ...
...And 2 more matches
Providing Command-Line Options - Archive of obsolete content
You can learn more about how the command line is interpreted by looking at the documentation for the nsICommandLine interface. ...
... * @param aChromeURISpec a string specifying the URI of the window to open. * @param aArgument an argument to pass to the window (may be null) */ fun...
...Typical command-line handlers use a // category that begins with the letter "m". entry: "m-myapp" }], QueryInterface:
XPCOMUtils.generateQI([ Ci.nsICommandLineHandler ]), /* nsICommandLineHandler */ handle : function clh_handle(cmdLine) { try { ...
...And 2 more matches
What XULRunner Provides - Archive of obsolete content
The goal of XULRunner is to provide a solution for deploying XUL applications (primarily Firefox and Thunderbird), as well as providing an embedding mechanism. ...
...terface for installing, uninstalling, and upgrading XUL applications. See the wikimo:XUL:Installation Story. ...
... What's out XULRunner will not supply: Bookmarks or History UI (must be managed by the application/embedder) XForms (XForms will be available as an extension) ...
...And 2 more matches
RDF in Mozilla FAQ - Archive of obsolete content
ource. Datasources may be loaded via the RDF service using the GetDataSource() method. If the URI argument refers to an RDF/XML file's URL, then the RDF service will create an RDF/XML datasource and asynchronously parse it. The datasource will remain "cached" until the last reference to the datasource is released. If the URI argument refers to a built-in datasource, the RDF service will use the
XPCOM Component Manager to load a component whose ContractID is constructed using the "special" URI and the well-known prefix@mozilla.org/rdf/datasource;1?name=</code>. For example, rdf:foo Would load: @mozilla.org/rdf/datasource;1?name=foo As with RDF/XML datasources, a datasource that is retrieved this way is "cached" by the RDF service until the last reference is dropped. How do I create a d...
..."] .getService(Components.interfaces.nsIRDFService); // ...and from it, get the datasource. Make sure that your web server // dishes it up as text/xml (recommended) or text/rdf! var ds = RDF.GetDataSource("http://www.mozilla.org/some-rdf-file.rdf"); // Note that ds will load asynchronously, so assertions will not // be immediately available Alternatively, you can create one directly using the
XPCOM Component Manager, as the following code fragment illustrates: // Create an RDF/XML datasource using the
XPCOM Component Manager var ds = Components .classes["@mozilla.org/rdf/datasource;1?name=xml-datasource"] .createInstance(Components.interfaces.nsIRDFDataSource); // The nsIRDFRemoteDataSource interface has the interfaces // that we need to setup the datasource. var remote = ds.Query...
...urce. How do I access "built-in" datasources? A built-in datasource is a locally-installed component that implements nsIRDFDataSource. For example, the bookmarks service. First, check here to make sure you will be allowed to access a built-in datasource. There are several security restrictions on accessing built-in datasources from "untrusted" XUL and JS. Since a built-in datasource is just an
XPCOM component, you can instantiate it directly using the XPConnect component manager. // Use the component manager to get the bookmarks service var bookmarks = Components. classes["@mozilla.org/rdf/datasource;1?name=bookmarks"]. getService(Components.interfaces.nsIRDFDataSource); // Now do something interesting with it... if (bookmarks.HasAssertion( RDF.GetResource("http://home.netscape.
...And 2 more matches
Debugging on Windows
String=<mData,s> nsCAutoString=<mData,s> nsRect=x=<x,d> y=<y,d> width=<width,d>; height=<height,d> nsStaticAtomWrapper=<mStaticAtom->mString,s> nsIAtom=<mString,su> ; the following are not necessary in vc8 nsCOMPtr<*>=<mRawPtr,x> nsRefPtr=<mRawPtr,x> nsAutoPtr=<mRawPtr,x> After you have made the changes and saved the file, you will need to restart Visual C++ for the changes to take effect. ...
...*>=<mRawPtr,x> nsRefPtr=<mRawPtr,x> nsAutoPtr=<mRawPtr,x> After you have made the changes and saved the file, you will need to restart Visual C++ for the changes to take effect. For
XPCOM Strings (the "external" string API) you can use the following values: ;; Mozilla (1.9) ; Internal Strings nsAString_internal=<mData,su>, length=<mLength,u> nsACString_internal=<mData,s>, length=<mLength,u> ;
XPCOM Strings nsAString=<nsStringContainer.v,su>, length=<nsStringContainer.d1,u> nsACString=<nsCStringContainer.v,s>, length=<nsCStringContainer.d1,u> nsStringContainer=<v,su>, length=<d1,u> nsCStringContainer=<v,s>, length=<d1,u> There is a more extensive version of this file in progress in AutoExpForVC8. Avoiding stepping into certain functions You can avoid stepping into certain functions, such...
...ebugging output until you flush or close the file handle. Disabling ASSERTIONS There are basically two ways to disable assertions. One requires setting an environment variable, while the other affects only the currently running program instance in memory. Environment variable There is an environment variable that can disable breaking for assertions. ...
...And 2 more matches
JavaScript Tips
RDFResource) return target.Value; if (target instanceof Components.interfaces.nsIRDFLiteral) return target.Value; return null; Don't test the return value of QueryInterface, it always returns the original variable if it succeeds. XPConnect knows all about tearoffs and modifies the object that you QueryInterface or instanceof to cache all its known interfaces. ...
...f Components.interfaces.nsIRDFLiteral) return target.Value; return null; Don't test the return value of QueryInterface, it always returns the original variable if it succeeds. XPConnect knows all about tearoffs and modifies the object that you QueryInterface or instanceof to cache all its known interfaces. When passing an object to an
XPCOM method it is helpful if the object you pass is an
XPCOM object, so that the C++ method access a C++ object. ...
...earoffs and modifies the object that you QueryInterface or instanceof to cache all its known interfaces. When passing an object to an
XPCOM method it is helpful if the object you pass is an
XPCOM object, so that the C++ method access a C++ object. However, this is not always necessary or desirable. For instance the offline observer declared above is a JavaScript object that is registered with an
XPCOM object, so that the call back from
XPCOM executes the JavaScript method. Some
XPCOM methods expect an object that implements several interfaces thus requiring you to write a QueryInterface method. However, in JavaScript this is quite simple even in the case of a weak reference which in C++ requires a helper class: var weakObserver = { QueryInterface: function QueryInterface(aIID) { if (aI...
...And 2 more matches
DMD
heap these blocks represent. Within each section, records are listed from largest to smallest. Once-reported and twice-reported stack trace records also have stack traces for the report point(s). ...
...o have stack traces for the report point(s). ...
.../njn/moz/mi2/
xpcom/base/nsCycleCollector.cpp:3008) 0x7f6860fdfe02 #03: nsPurpleBuffer::SizeOfExcludingThis(unsigned long (*)(void const*)) const (/home/njn/moz/mi2/
xpcom/base/nsCycleCollector.cpp:933) 0x7f6860fdb7af #04: nsCycleCollector::SizeOfIncludingThis(unsigned long (*)(void const*), unsigned long*, unsigned long*, unsigned long*, unsigned long*, unsigned long*) const (/home/njn/moz/mi2/
xpcom/base/nsCycleCollector.cpp:3029) 0x7f6860fdb6b1 #05: CycleCollectorMultiReporter::CollectReports(nsIMemoryMultiReporterCallback*, nsISupports*) (/home/njn/moz/mi2/
xpcom/base/nsCycleCollector.cpp:3075) 0x7f6860fde432 #06: nsMemoryInfoDumper::DumpMemoryReportsToFileImpl(nsAString_internal const&) (/home/njn/moz/mi2/
xpcom/base/nsMemoryInfoDumper.cpp:626) 0x7f6860fece79 #07: nsMemoryInfoDumper::...
...And 2 more matches
Building the WebLock UI
In this chapter, however, we are going to be building a user interface for the WebLock component that's meant to be added to the existing Mozilla browser[other-mozlike-browsers]. ...
...markup map to widgets in the interface that Gecko renders in a fairly straightforward way - so, for instance, the root element of an application window is the element <window/>, the root element of the dialog we'll be creating here is <dialog/>, and so forth. ...
... - so, for instance, the root element of an application window is the element <window/>, the root element of the dialog we'll be creating here is <dialog/>, and so forth. Within a XUL application file, elements like <button/>, <menu/>, and <checkbox/> can be hooked up to an event model, to scripts, and to the
XPCOM interfaces that carry out a lot of the browser functionality in Mozilla. In Using
XPCOM Components you saw how
XPCOM objects are reflected into the interface layer as JavaScript objects. In this chapter, now that we've created the WebLock component and made it available to
XPCOM, we create the UI that actually instantiates the WebLock component and uses its methods to control page loading in the browser. In the previous section, we outlined the JavaScript that interacts with the We...
...And 2 more matches
Mozilla internal string guide
s a C++ class hierarchy to pass string data, rather than using raw pointers. This guide documents the string classes which are visible to code within the Mozilla codebase (code which is linked into libxul). Introduction The string classes are a library of C++ classes which are used to manage buffers of wide (16-bit) and narrow (8-bit) character strings. The headers and implementation are in the
xpcom/string directory. All strings are stored as a single contiguous buffer of characters. The 8-bit and 16-bit string classes have completely separate base classes, but share the same APIs. As a result, you cannot assign a 8-bit string to a 16-bit string without some kind of conversion helper class or routine. For the purpose of this document, we will refer to the 16-bit string classes in class docu...
...nish(). It takes two arguments: the new logical length of the string (which must not exceed the capacity retuned by the Length() method of the handle) and a boolean indicating whether it's OK to attempt to reallocate a smaller buffer in case a smaller mozjemalloc bucket could accommodate the new logical length. Helper Classes and Functions Converting Cocoa strings Use mozilla::CopyCocoaStringTo
XPCOMString() in mozilla/MacStringHelpers.h to convert Cocoa strings to
XPCOM strings. Searching strings - looking for substrings, characters, etc. FindInReadable() is the replacement for the old string.Find(..). The syntax is: PRBool FindInReadable(const nsAString& pattern, nsAString::const_iterator start, nsAString::const_iterator end, nsStringComparator...
...put is known to be strictly ASCII. Often a conversion to UTF-8 is more appropriate. See ToNewUTF8String below. char* ToNewUTF8String(nsAString&) - Allocates a new char* buffer containing the UTF-8 encoded version of the given nsAString. See Unicode Conversion for more details and for better ways that don't require you to manage the memory yourself. These methods return a buffer allocated using
XPCOM's allocator instead of the traditional allocator (malloc, etc.). Outside of libxul you should use NS_Free to deallocate the result when you no longer need it, inside libxul free() is preferred.. Substrings (string fragments) It is very simple to refer to a substring of an existing string without actually allocating new space and copying the characters into that substring. Substring() is the pre...
...And 2 more matches
Components.Constructor
Summary Creates a JavaScript function which can be used to create or construct new instances of
XPCOM components. Syntax var func = [ new ] Components.Constructor(contractID [, interfaceName [, initializer ] ]); Parameters contractID A string containing the contract ID of the component interfaceName If given, nsISupports.QueryInterface() will be called on each newly-created instance with the interface named by this string initializer If given, a string containing the name of a function which will be called on the newly-created instance, using the arguments provided to the created function when called Description Components.Constructor() is a handy shortcut for creating instances of
XPCOM components. It eliminates the clutter of typing Components.classes, Components.inter...
...tion which will be called on the newly-created instance, using the arguments provided to the created function when called Description Components.Constructor() is a handy shortcut for creating instances of
XPCOM components. It eliminates the clutter of typing Components.classes, Components.interfaces, createInstance, and so on every time you wish to create an instance. It also gives creation of
XPCOM objects more JavaScript-like syntax. ...
... instances of
XPCOM components. It eliminates the clutter of typing Components.classes, Components.interfaces, createInstance, and so on every time you wish to create an instance. It also gives creation of
XPCOM objects more JavaScript-like syntax. Another important benefit is that it precomputes some of the computation it does, so using a function returned from Components.Constructor() to create
XPCOM objects is faster than creating the object from base principles, as demonstrated below. (This benefit is also partly a result of having to travel through the layer between the JavaScript engine and
XPCOM fewer times.) The behavior of functions returned by Components.Constructor() varies depending upon the arguments given to Components.Constructor() when called. If only one argument is given, tha...
...And 2 more matches
Development
Build Instructions The build instructions are available here: Building Java
XPCOM. Bugs All Java
XPCOM bugs are tracked in Bugzilla, using the "Core" product and "Java to
XPCOM Bridge" component. ...
... Source The latest source code is available on the Mozilla trunk, in the extensions/java/
xpcom directory. Build Instructions The build instructions are available here: Building Java
XPCOM. ...
... Source The latest source code is available on the Mozilla trunk, in the extensions/java/
xpcom directory. Build Instructions The build instructions are available here: Building Java
XPCOM. ...
...And 2 more matches
Building an Account Manager Extension
Step 1: Implementing nsIAccountManagerExtension As first step we have to implement the nsIAccountManagerExtension. We name the Extension "devmo-account" and state that it is located in the Chrome Package "example@mozilla.org". Furthermore we show the new panel only for IMAP accounts... ...
...s constructor function DevmoAccountManagerExtension() {}; // class definition DevmoAccountManagerExtension.prototype = { name : "devmo-account", chromePackageName : "example@mozilla.org", showPanel: function(server) { //this panel is only shown for imap accounts... if (server.type == \"imap\") return true; return false; }, QueryInterface:
XPCOMUtils.generateQI([ Components.interfaces.nsIMsgAccountManagerExtension ]) } Step 2: Building a Component We convert the interface to a
XPCOM Component and register it in the component manager as Account Manager Extension. Therefore we add the following code to the previous. The JavaScript file has to be saved either in the extension's or Thunderbird's component directory. // Defin...
...ccountManagerExtension.prototype.classDescription = "Devmo Account Manager Extension"; // ... textual unique identifier or rendez-vous point in the category manager. ...
...And 2 more matches
Component; nsIPrefBranch
branch at which to start enumerating the child preferences. Pass in "" to enumerate all preferences referenced by this branch. aCount Optional from Gecko 2.0 Receives the number of elements in the array. aChildArray Receives the array of child preferences. getComplexValue() Called to get the state of an individual complex preference. A complex preference is a preference which represents an
XPCOM object that can not be easily represented using a standard boolean, integer or string value. void getComplexValue( in string aPrefName, in nsIIDRef aType, [iid_is(aType), retval] out nsQIResult aValue ); Parameters aPrefName The complex preference to get the value of. aType The
XPCOM interface that this complex preference represents. Interfaces currently supported are: NsILocal...
... getIntPref() Called to get the state of an individual integer preference. long getIntPref( in string aPrefName, [optional] in long aDefaultValue ); Parameters aPrefName The integer preference to get the value of. ...
... storing data separately, for example in a flat file or an sqlite database. void setStringPref( in string aPrefName, in utf8string aValue ); Parameters aPrefName The string preference to set. aValue The UTF-8 string value to set the preference to. setComplexValue() Called to set the state of an individual complex preference. A complex preference is a preference which represents an
XPCOM object that can not be easily represented using a standard boolean, integer or string value. void setComplexValue( in string aPrefName, in nsIIDRef aType, in nsISupports aValue ); Parameters aPrefName The complex preference to set the value of. aType The
XPCOM interface that this complex preference represents. Interfaces currently supported are: NsILocalFile NsISupportsString...
...And 2 more matches
nsIVariant
We mark the interface [scriptable] so that JS can use methods that refer to this interface. But we mark all the methods and attributes [noscript] since any nsIVariant object will be automatically converted to a JS type anyway. ...
...tributes [noscript] since any nsIVariant object will be automatically converted to a JS type anyway. ...
... AUTF8String getAsAUTF8String(); Native code only! PRBool getAsBool(); Native code only! char getAsChar(); Native code only! DOMString getAsDOMString(); Native code only! double getAsDouble(); Native code only! float getAsFloat(); Native code only! nsresult getAsID(out nsID retval); Violates the
XPCOM interface guidelines PRInt16 getAsInt16(); Native code only! PRInt32 getAsInt32(); Native code only! PRInt64 getAsInt64(); Native code only! PRUint8 getAsInt8(); Native code only! void getAsInterface(out nsIIDPtr iid, [iid_is(iid), retval] out nsQIResult iface); Native code only! nsISupports getAsISupp...
...And 2 more matches
wrappedJSObject
nect wrappers. When available, it lets you access the JavaScript object hidden by the wrapper. There are two kinds of XPConnect wrappers that support the wrappedJSObject property: XPCNativeWrappers which are used to protect the chrome code working with content objects. See XPCNativeWrapper for detailed documentation. Regular XPConnect wrappers which you can encounter, for example, when using
XPCOM components implemented in JS. This article focuses on the latter kind of wrappers, which hide any properties or methods on the component that are not part of the supported interfaces as declared in xpidl. The rest of this article demonstrates what XPConnect wrappers do and how wrappedJSObject can be used to bypass them. Example component To see how the wrappedJSObject property works, we need...
...implemented in JS. This article focuses on the latter kind of wrappers, which hide any properties or methods on the component that are not part of the supported interfaces as declared in xpidl. The rest of this article demonstrates what XPConnect wrappers do and how wrappedJSObject can be used to bypass them. Example component To see how the wrappedJSObject property works, we need an example
XPCOM component implemented in JS. See How to Build an
XPCOM Component in Javascript for details on creating one. For simplicity we omit the component registration code. Suppose we register the component below with the @myself.com/my-component;1 contract. // constructor function HelloWorld() { }; HelloWorld.prototype = { hello: function() { return "Hello World!"; }, QueryInterface: functi...
...rn "Hello World!"; }, QueryInterface: function(aIID) { if (!aIID.equals(Components.interfaces.nsISupports) && !aIID.equals(Components.interfaces.nsIHelloWorld)) throw Components.results.NS_ERROR_NO_INTERFACE; return this; } }; XPConnect wrapping Now let's get a reference to our component. ...
...And 2 more matches
Xptcall Porting Guide
Overview xptcall is a library that supports both invoking methods on arbitrary
xpcom objects and implementing classes whose objects can impersonate any
xpcom interface. It does this using platform specific assembly language code. This code needs to be ported to all platforms that want to support xptcall (and thus mozilla). ...
... Overview xptcall is a library that supports both invoking methods on arbitrary
xpcom objects and implementing classes whose objects can impersonate any
xpcom interface. It does this using platform specific assembly language code. This code needs to be ported to all platforms that want to support xptcall (and thus mozilla). ...
...dex(nsISupports* that, PRUint32 methodIndex, PRUint32 paramCount, nsXPTCVariant* params); Calling code is expected to supply an array of nsXPTCVariant structs. These are discriminated unions describing the type and value of each parameter of the target function. The platform specific code then builds a call frame and invokes the method indicated by the index methodIndex on the
xpcom interface that. Here are examples of this implementation for Win32 and Linux x86, NetBSD x86, and FreeBSD. These implementations use the basic strategy of: figure out how much stack space is needed for the params, make the space in a new frame, copy the params to that space, invoke the method, cleanup and return. C++ is used where appropriate, Assembly language is used where necessary. Inline as...
...And 2 more matches
Mozilla technologies
a projects hosted in the Mercurial repositories can be searched and viewed online using Searchfox, a fast indexed search engine that runs on AWS.XML ExtrasThe XML Extras module contains several features that allow developers to treat XML as data i.e. not as just another document format. ...
...he XML Extras module contains several features that allow developers to treat XML as data i.e. not as just another document format. The module is structured as a drop-in component and exposes its XML-as-data features both to JavaScript and C++/
XPCOM users. The XML Extras module is built by default on all platforms, and is included in the browser installers so it is available in the nightly builds.
XPCOMXPCOM is a cross platform component object model, similar to Microsoft COM. ...
...ormat. The module is structured as a drop-in component and exposes its XML-as-data features both to JavaScript and C++/
XPCOM users. The XML Extras module is built by default on all platforms, and is included in the browser installers so it is available in the nightly builds.
XPCOMXPCOM is a cross platform component object model, similar to Microsoft COM. ...
...And 2 more matches
Handling Preferences - Archive of obsolete content
ence appear in about:config after installing the extension. Just type "xulschool" in the filter box to see your new preference. Note: Always begin your preference names with "extensions", followed by some namespacing and finally the actual name of the preference. Name parts are normally separated by dots. Now let's look at how we actually manage the preference values. Managing preferences with
XPCOM We use the Preferences Service in order to get and set preference values: this._prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); // ... get count() { return this._prefService.getIntPref("extensions.xulschoolhello.message.count"); }, increment : function() { let currentCount = this._prefService.getIntPref("extensions.xulschoolhello.message.count");...
...o.message.count"); }, increment : function() { let currentCount = this._prefService.getIntPref("extensions.xulschoolhello.message.count"); this._prefService.setIntPref("extensions.xulschoolhello.message.count", currentCount + 1); } One important thing to keep in mind is that the "get" methods of the service can throw an exception if the preference is not found. ...
...his._prefService.setIntPref("extensions.xulschoolhello.message.count", currentCount + 1); } One important thing to keep in mind is that the "get" methods of the service can throw an exception if the preference is not found. If you are going to use
XPCOM, you should always set a default value to your preferences, or use a try / catch block to prevent unhandled errors. ...
...hello.message.count", currentCount + 1); } One important thing to keep in mind is that the "get" methods of the service can throw an exception if the preference is not found. If you are going to use
XPCOM, you should always set a default value to your preferences, or use a try / catch block to prevent unhandled errors. ...
Intercepting Page Loads - Archive of obsolete content
t is downloaded, and before the user sees anything in the tab. HTTP Observers Another common way of detecting and intercepting loads is using HTTP observer topics. This is how the Tamper Data extension and others do it. HTTP notifications are fired for all HTTP requests originating from Firefox. They are window-independent, so it is better to keep your observer code in non-chrome objects (your
XPCOM service or jsm module). Otherwise you have to make sure to avoid duplicated work if you have 2 or more windows open. There are 2 HTTP topics you can listen to, as specified in the Observer Notifications page: Topic Description http-on-modify-request Called as an http request is made. The channel is available to allow you to modify headers and such. http-on-exami...
...ase, the URL can be obtained from aRequest.name. Make sure you access it from inside the state validation if condition. There may be other cases where accessing this property will throw an exception. Canceling the request works just like with onLocationChange. See "Recognizing page load failure" at mozilla.dev.extensions for tips on detecting connection failures and HTTP response codes.
XPCOM Solutions There are a couple more solutions you may be interested in trying if the previous ones are insufficient. These require creating
XPCOM components that implement existing Firefox interfaces. They may be useful in case you have most of your application logic in
XPCOM, or if you absolutely need a single point of inspection for loads. The previously explained solutions are enough for most c...
... that implement existing Firefox interfaces. They may be useful in case you have most of your application logic in
XPCOM, or if you absolutely need a single point of inspection for loads. The previously explained solutions are enough for most cases, so these ones will be mentioned briefly. Document Loader Service nsIDocumentLoader is nothing but a global Web Progress Listener. You can create an
XPCOM component that extends nsIWebProgressListener and use the addProgressListener method in the service to include it. Everything mentioned before applies here as well, except you'll be receiving all the events for all tabs and windows in a single object, and you don't have to worry about adding and removing listeners every time a tab is opened or closed. This also has the advantage of detecting pag...
...a web filtering extension, you should keep in mind that XUL windows such as the DOM Inspector window and the Add-ons Manager window allow (limited) web navigation. Other extensions might add XUL windows that allow navigation as well, so in those cases it's best to use a global solution like this one. Content Policy Finally, there is the option of implementing nsIContentPolicy. You can create an
XPCOM component that extends nsIContentPolicy and register it to the "content-policy" category using the nsICategoryManager. The nsIContentPolicy.shouldLoad() method is the only one in this interface that is really useful. It actually allows for cleaner-looking code than most of the previously seen solutions, because you get the content URI directly as an argument, and you indicate if the content shou...
Observer Notifications - Archive of obsolete content
<< PreviousNext >> Sometimes you need your code to send a message to other parts of your code. For example, you might want to notify that a task is completed, and then several different actions must be performed. You could do that by calling all those functions directly, but
XPCOM offers you a better and cleaner way to achieve that using observers and the observer service. An observer is an object that is responsible to observe (wait for) notifications and then to carry out subsequent actions. ...
...s you a better and cleaner way to achieve that using observers and the observer service. An observer is an object that is responsible to observe (wait for) notifications and then to carry out subsequent actions. To create an observer, you need to implement the nsIObserver interface. The interface has only one method observe() which takes three parameters. The first parameter (subject) can be any
XPCOM object, the second parameter is a notification topic, and the final parameter is a string that further describes the notification. This example code shows you what an implementation of the nsIObserver interface looks like: let testObserver = { observe : function(aSubject, aTopic, aData) { if (aTopic == "xulschoolhello-test-topic") { window.alert("Data received: " + aData); } ...
...veObserver method. The method takes the observer object and notification topic as parameters. observerService.removeObserver(testObserver, "xulschoolhello-test-topic"); After you have registered some observers to listen to a notification topic, you can then use the notifyObservers method to send a notification to all of them. The method takes three parameters. The first parameter can be any
XPCOM object to pass to those observers (can be null), the second parameter is the notification topic and the last parameter is an additional string to pass to those observers (can be null). observerService.notifyObservers(null, "xulschoolhello-test-topic", "hello"); Non-chrome to chrome communication Non-chrome to chrome communication is one of the main uses of observers. By non-chrome we mean ...
...servers (can be null), the second parameter is the notification topic and the last parameter is an additional string to pass to those observers (can be null). observerService.notifyObservers(null, "xulschoolhello-test-topic", "hello"); Non-chrome to chrome communication Non-chrome to chrome communication is one of the main uses of observers. By non-chrome we mean JavaScript Code Modules or
XPCOM. As we saw in previous sections, you can use JavaScript Code Module and
XPCOM objects very easily from the chrome. But given that chrome is window-dependent and non-chrome objects are not, it's tricky to send a message to the chrome. You would have to invoke a method for the chrome objects in all windows. It's much easier to use observers in this case. Let's see the following example code on how...
Setting Up a Development Environment - Archive of obsolete content
Makefile specifies which profile folder the add-on will be reinstalled to. This is set in the profile_dir variable (set to "xulschool-dev" in this case). When creating a development profile for your add-on, make sure you choose an easy name for the profile folder, and set it in your Makefile in order to take advantage of the install command. Building IDL files Some extensions require developing
XPCOM components to add certain advanced functions. There's a section dedicated to
XPCOM in this tutorial, but we'll briefly discuss the impact it has on building the extension. You can skip this section and keep it present as a reference in case you do need to use
XPCOM in your project.
XPCOM interfaces are defined using IDL files. These are text files that define the attributes and methods in one or...
... default executable path, and also add a variable called GECKO_SDK, that points to your SDK build: export GECKO_SDK=/path/to/your/sdk Our build system should pick it up from there. To make it work in Komodo in Unix-based systems, we add the command to the .bash_login file in the home directory, and we modify the commands to this: bash -c ". ~/.bash_login; make" An example project with
XPCOM components is included in the
XPCOM section. There is also a mention about building C++
XPCOM, which is something much more complicated. Signing extensions In order to provide additional security for your users, you can choose to add a signature to your extension. The signature verifies that you are the author of this extension, and it can only be done if you have a valid certificate provided b...
...very useful in this case. You can set breakpoints, step in and out of methods, and even get profiling information from Javascript execution. You can inspect variables, keep track of watch expressions, and evaluate arbitrary JS at any point in execution. This extension has seen little maintenance in quite some time, so it is very buggy. It is specially unreliable when debugging code in Javascript
XPCOM and XBL files. Nevertheless, it is a valuable tool when trying to figure out why a certain function is misbehaving. Tamper Data Tamper Data intercepts HTTP requests and their responses. It allows you to cancel them and even replace payload data before it is sent. There are several similar extensions, such as Live HTTP Headers, but Tamper Data is the one that we use the most. We'll cover more on...
...ory leaks have always been a big criticism drawn against Firefox. Mozilla has proven with time that they take memory usage seriously, improving performance on several critical areas and removing all kinds of memory leaks. However, extensions are also capable of causing memory leaks. If you want your extension to be included in the Mozilla Add-ons site, you better not have any memory leaks. Using
XPCOM in JavaScript has some guidelines you should follow to avoid them. One of the most common errors developers make is to register a JS event listener or observer, and never removing it. The simple practice of always including removal code for everything you add makes a big difference. To make sure your extension doesn't leak, you should use the Leak Monitor extension when testing it. Always test o...
List of Mozilla-Based Applications - Archive of obsolete content
blog post mentions a reference to Mozilla being used but I couldn't find more information about it. ...
...la SpiderMonkey and formerly called wxJavaScript Gnome operating system Gnome 3 will use SpiderMonkey through Gjs Google AdWords Editor editor Google Gadgets for Linux Google's Desktop Widget engine Uses XULRunner according to the Build Instructions Grani Grain sizing assessment tool According to this wiki page Grani is based on XUL and
XPCOM Daim gwt-mosaic-xul XUL builder for Google Web Tools Hachette's Multimedia Encyclopedia electronic encyclopedia This product was using Mozilla in 2004 but I'm not sure if new version still does HacketyHack little coders Helma web application framework Uses Mozilla Rhino Holt McDougal CD-ROMs educational CD-ROMs Activity ...
...(Product was formerly known as Lombardi Teamworks) IceDragon fast, secure and feature-rich Internet browser Based on Firefox IDA e-Learning authoring system About 200 users IMVU 3d chat client Incredimail mail client Seems to use XULRunner Instantbird IM client XULRunner application ItsNat Jav...
... using mailnews code but don't have any information to link to. Feel free to supply references. ...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
urce RPM (check bug 295329) ; patch: [root@b008-02 SOURCES]# cat thunderbird-autoconfigAndLdap.patch diff -ur thunderbird-3.0/configure thunderbird-3.0.autoldap/configure --- thunderbird-3.0/configure 2009-06-29 11:37:21.677372297 +0200 +++ thunderbird-3.0.autoldap/configure 2009-06-29 14:41:11.547435040 +0200 @@ -12855,7 +12855,7 @@ MOZ_FEEDS=1 MOZ_JSDEBUGGER=1 MOZ_JSLOADER=1 -MOZ_LDAP_
XPCOM= +MOZ_LDAP_
XPCOM=1 MOZ_MAIL_NEWS= MOZ_MORK=1 MOZ_MORKREADER= And set --enable-extensions=pref in mozconfig file, in fedora source RPM it is: [root@b008-02 SOURCES]# grep enable-extensions /root/rpmbuild/SOURCES/thunderbird-mozconfig ac_add_options --enable-extensions=pref It seems worse this time , as even after applying those compilation options mentioned above, I now get the following e...
...ROR_NOT_INITIALIZED) [nsILDAPURL.spec]" nsresult: "0xc1f30001 (NS_ERROR_NOT_INITIALIZED)" location: "JS frame :: file:////usr/lib/thunderbird-3.0b2/defaults/autoconfig/prefcalls.js :: getLDAPAttributes :: line 174" data: no] bug 295329 had been re-opened . AutoConfig Option and LDAP Support in Thunderbird 1.5.x Fortunately, AutoConfig is now part of Thunderbird default packages. MOZ_LDAP_
XPCOM=1 and MOZ_EXTENSIONS_DEFAULT="wallet spellcheck xmlextras pref webservices universalcharset auth" are now present in the default configure script. See bug 295329 for details. Add the AutoConfig Option for Old Thunderbird 1.0.x By default, AutoConfig did not make part of the binaries distribution of Thunderbird (1.0.x). It was apparently supposed to increase the load of the binary for a feature ...
...verride it. function displayError(title, msg) { log.debug(title + ": " + msg); alerts.showAlertNotification("chrome://branding/content/icon48.png", title, msg); } Firefox It's the same principles as for firefox as it was described above for thunderbir. Binary distributions should now include support for AutoConfig (pref extension!) but unfortunately not for LDAP calls :-( (cf. MOZ_LDAP_
XPCOM=1). It is not vital in Firefox as it is for us in Thunderbird (need to get the cn and email address to set email account, which are not available by default in the environment variables). However I could be useful to get LDAP values for Firefox extra config, for example to set the default home page to the labeledURI LDAP attribute of the user. Firefox 22 omni.jar archive file became omni.ja sin...
...cript argument arg 0 [nsISupports.QueryInterface]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: prefcalls.js :: getLDAPAttributes :: line 177" data: no] AutoConfig (pref) and LDAP Support in Packages Add LDAP Support in Firefox 1.5 A least from Firefox 1.5, AutoConfig is compiled by default (cf. browser, MOZ_EXTENSIONS_DEFAULT="pref...") but not LDAP (MOZ_LDAP_
XPCOM=1). You need to recompile the package to get it, cf. bug 295329. Add AutoConfig and LDAP Support in Firefox 1.0.x Add pref extension (--enable-extensions=pref) and remove --disable-ldap from mozconfig file. One can check how Firefox has been compiled by opening about:buildconfig (don't know the equivalent for Thunderbird! how as it been compiled?) about:buildconfig Build platform target i686-...
The new nsString class implementation (1999) - Archive of obsolete content
In fact, it's very unlikely this is really the page you want. If you happen to see dbaron lying around somewhere, please direct him here so he can fix this message. In the meantime, try the
XPCOM string guide--but note that that article bears a warning of its own! This document is intended to briefly describe the new nsString class architecture, and discuss the implications on memory management, optimizations, internationalization and usage patterns. Disclaimer: I absolutely hate string classes. No one has ever devised one that more than 2 programmers can agree on. So, why then am I proposing this? Well, nsString has served us well so far, but it's in need of a facelift. And
XPCOM has really taken off, so nsString needs to be brought into alignment. Justification The nsString class i...
... a few implementation details which need to be addressed and that are the subject of this document. ...
... static void EnsureCapacity(nsStrIm...
...acter storage model. This will allow programmers to use the nsString API's like a standard char* without incurring the 2-byte per character overhead. This class fully interoperates with nsString, nsAutoString and nsStrImpl. nsIString Naturally we will need include an nsIString interface onto the nsStrImpl/nsString classes. I won't repeat it's interface here since it is basically a restatement (in
XPCOM terms) of the nsString interface. Usage Patterns How To Use These Classes To increase the portability, thread and process safety of Gecko, I suggest the following rules regarding the use of each of our string class derivatives: <center> String Class</center> <center> Where To Use</center> nsStrImpl Use to pass strings between modules who have li...
Building XULRunner with Python - Archive of obsolete content
This page describes how to build and use XULRunner with the Python extension on Windows and while generally useful it is written based on experiences with accessibility projects. See also XULRunner. Or, if you are interested in working with XULRunner with Python on Linux, see Mark Lise's Post With the Python extensions enabled XULRunner provides python script access to the DOM and
XPCOM in addition to the usual Java Script. This gives access to Python features and modules and builds on Mark Hammond's py
XPCOM work from Active State.
XPCOM components can also be created in Python. Currently (Mar 07) Python is not enabled by default so a custom build of Mozilla is needed. This page provides instructions in the hope of eliminating much trial and error. You should also read the the developer docu...
...Of particular interested is access to MSAA and IAccessible2 via the Python comtypes package. ...
...es shown. It effectively specifies a release build that is not particularly suitable for debugging XULRunner itself. It uses the trunk (or latest) code in CVS so may be unstable. ...
...\2.5" > nul 2>&1 if errorlevel 1 ( echo Python 2.5 was not found. ...
Archived Mozilla and build documentation - Archive of obsolete content
that have little to no effect on performance when not in use and very little when active. Probe data can be collected with scripts written in D (no, not that one). Mozilla DTrace support has been added by the Sun DTrace team and can be used on Solaris 10 and Mac OS X 10.5. Embedding FAQ Embedding Mozilla in a Java Application using Java
XPCOM XULRunner ships with the Java
XPCOM component, which allows Java code to interact with
XPCOM objects. As you will see in this article, working with
XPCOM objects in Java is not that much different than doing so in C++. Error Console The Error Console is a tool available in most Mozilla-based applications that is used for reporting error...
...pace and influence where other elements can be placed. The Space Manager is responsible for keeping track of where space is taken up and where it is available. This information is used by block layout to correctly compute where other floated elements should be placed, and how much space is available to normal in-flow elements that flow around the floated bits. ...
...other elements can be placed. The Space Manager is responsible for keeping track of where space is taken up and where it is available. This information is used by block layout to correctly compute where other floated elements should be placed, and how much space is available to normal in-flow elements that flow around the floated bits. Standalone
XPCOM Standalone
XPCOM is a tree configuration that builds a minimal set of libraries (shared mostly) that can be used to get all features of
XPCOM. The contents of this standalone
XPCOM in general are: Stress testing Consume.exe from the Windows Server 2003 Resource Kit Tools can consume various resources: physical memory, CPU time, page file, disk space and even the kernel pool. Alt...
... inserted into the editor. The XUL can be loaded from and saved to files. A XUL validator and the Error Console are both available to help debug problems. The help menu provides access to XUL information on MDC. There is even simple "keyword" help lookup for XUL elements. XULRunner XULRunner is a Mozilla runtime package that can be used to bootstrap XUL+
XPCOM applications that are as rich as Firefox and Thunderbird. It provides mechanisms for installing, upgrading, and uninstalling these applications. ...
Extentsions FAQ - Archive of obsolete content
How to customizes toolbar button to coexist in a toolbar palette and status bar? Option #3 Install Status Buttons 1.0 <https://addons.mozilla.org/firefox/1272/> "Lets you put toolbar buttons at either end of the status-bar. ...
...06 (? top) Any suggestions to remove tool tip appears on the menu it when it should not? What you described was a bug (https://bugzilla.mozilla.org/show_bug.cgi?id=147670). It looks like it has been fixed for Firefox version 2. What do I need to do to avoid deadlocks? Do I need to marshalinvokations to a particular thread? If so, how? Are there any fundamental rules related to threading in
XPCOM, and if so, where are these defined? DOM can only be accessed from the main thread. Also, check out this site to learn how to set up a proxy: http://www.mozilla.org/projects/
xpcom/Proxies.html How to test a tab has been closed or not? You can capture the even of tab closing. You can get the tab that is being closed. This should be enough for you. Is it possible to fix the size exactly a...
... http://developer.mozilla.org/en/docs...PCOM_Component Would anyone be able to suggest the best way to do source level debugging in a Firefox extension? In the Debug menu, uncheck Exclude Browser Files. Use the debugger by typing in a command like this: /break chrome://myextension/content/myfile.js 123...
...Thunderbird address book lacks. ...
Mozilla accessibility architecture
, the accessibility APIs use similar concepts, but use different method, constant and interfaces names. Given that there is a fair amount of commonality between accessibility API toolkits, it made sense to write of the code in a cross platform manner, and then deal with the platform differences on a consistent manner. The shared code makes itself available to the toolkit-specific code via generic
XPCOM interfaces that return information about objects we want to expose. All focusable nodes, tables and text have accessibility interfaces. We call these objects "accessible nodes". Each of these accessible nodes supports at minimum the generic cross-platform accessibility interface nsIAccessible (which provides a text name, enumerated role identifier and a set of state flags) and sometimes addition...
...mes additional interfaces. For example, tables support nsIAccessibleTable, text supports nsIAccessibleText and edit boxes support nsIEditableText., although this code has been moved into the ATK specific directories because it is not currently used in Windows. We will not rule out the possibility of supporting some of the rich ATK interfaces on Windows. The toolkit-specific classes then use these
XPCOM interfaces to gather information about the objects they want to expose, make any necessary changes, and then expose the information using Microsoft COM on Windows, or through GTK2's ATK API's on Linux and Unix. The assistive technology can then use this information in a number of ways. It can read in an entire document at once, look only pieces of a document related to recent events, or traverse ...
...name. For example, document specific code for each toolkit goes in nsDocAccessibleWrap: public nsDocAccessible. ...
...e iterate through all the dom nodes in the subtree, checking for nsIAccessNode entries in the cache for each dom node, shutting them down if they exist. This is better than just traversing the accessibles by using the member variables mFirstChild and mNextSibling, because that would miss nsAccessNode's that are not nsAccessible's. At program shutdown, when the nsAccessibilityService observes NS_
XPCOM_SHUTDOWN_OBSERVER_ID, it iterates through the doc accessibles in gGlobalDocAccessibleCache and destroys all of the doc accessibles them. Challenges of the Accessibility Cache There are some tricky issues when dealing with the accessibility cache: Remaining valid: changes in a given document, or the destruction of documents must update or shutdown parts of the cache. We use DOM mutation events...
Creating a Login Manager storage module
n (bug 106400) and Gnome Keyring Manager (bug 309807). You should start with the existing code if you want to implement that in your extension. To see some debugging output in the console set signon.debug to true using about:config. Sample JavaScript implementation The following code snippet is a JavaScript component that implements a dummy nsILoginManagerStorage interface. ...
...t signon.debug to true using about:config. Sample JavaScript implementation The following code snippet is a JavaScript component that implements a dummy nsILoginManagerStorage interface. See How_to_Build_an_
XPCOM_Component_in_Javascript for more details about JavaScript components. ...
...s; const Ci = Components.interfaces; Components.utils.import("resource://gre/modules/
XPCOMUtils.jsm"); function SampleLoginManagerStorage() {} SampleLoginManagerStorage.prototype = { classDescription: "Sample nsILoginManagerStorage implementation", contractID: "@example.com/login-manager/storage/sample;1", classID: Components.ID("{364a118c-747a-4f6d-ac63-2d2998e5a5c1}"), QueryInterface:
XPCOMUtils.generateQI([Ci.nsILoginManagerStorage]), // This registers the category for overriding the built-in nsILoginManagerStorage _
xpcom_categories: [ { category: "login-manager-storage", entry: "nsILoginManagerStorage" } ], // Console logging service, used for debugging. __logService : null, get _logService() { if (!this.__logService) this.__logService =...
...The category registration looks like this: nsCOMPtr<nsICategoryManager> cat = do_GetService(NS_CATEGORYMANAGER_CONTRACTID); NS_ENSURE_STATE(cat); cat->AddCategoryEntry("login-manager-storage", "nsILoginManagerStorage", kYourContractID, PR_TR...
Interface Compatibility
nd APIs are not yet complete. The stable version 1.0 of the Jetpack SDK is planned for later in 2010. Documented APIs which are shipped as part of the Jetpack SDK are designed to work in future versions of Firefox. Achieving this compatibility may require rebuilding the extension with a new version of the Jetpack SDK. ...
... Between major releases, there is no guarantee of interface stability. Changes should not be taken lightly, however: especially if a change is likely to affect many extensions, the change should try to maintain backwards compatibility by using optional/default parameters or other JavaScript techniques. ...
..., there is no guarantee of interface stability. Changes should not be taken lightly, however: especially if a change is likely to affect many extensions, the change should try to maintain backwards compatibility by using optional/default parameters or other JavaScript techniques. ...
... compatibility by using optional/default parameters or other JavaScript techniques. Where appropriate, new APIs should be designed so that they are compatible with future plans, and clients do not need
XPCOM boilerplate. This may involve using JavaScript modules, passing named parameters using objects, or other similar techniques. Binary Interfaces Traditionally, Mozilla has maintained a set of
XPCOM interfaces and functions with the @status FROZEN marking. Using these interfaces, and using dynamic calls to QueryInterface, it has been possible to write binary
XPCOM components which were compatible with multiple versions of Firefox. Beginning with Mozilla 2 (Firefox 4), this will no longer be supported: all @status markings have been removed, and extensions that use binary components will need...
Using JavaScript code modules
JavaScript code modules are a concept introduced in Gecko 1.9 and can be used for sharing code between different privileged scopes. Modules can also be used to create global JavaScript singletons that previously required using JavaScript
XPCOM objects. A JavaScript code module is simply some JavaScript code located in a registered location. The module is loaded into a specific JavaScript scope, such as XUL script or JavaScript
XPCOM script, using Components.utils.import() or Components.utils["import"](). Creating a JavaScript code module A very simple JavaScript module looks like this: var EXPORTED_SYMBOLS = ["foo", "bar"]; function foo() { return "foo"; } var bar = { name : "bar", size : 3 }; var dummy = "dummy"; Notice that the module uses normal JavaScript to create functions,...
.... Scope 1: Components.utils.import("resource://app/my_module.jsm"); alert(bar.size + 3); // displays "6" bar.size = 10; Scope 2: Components.utils.import("resource://app/my_module.jsm"); alert(foo()); // displays "foo" alert(bar.size + 3); // displays "13" This sharing behavior can be used to create singleton objects that can share data across windows and between XUL script and
XPCOM components. Note: Each scope that imports a module receives a by-value copy of the exported symbols in that module. Changes to the symbol's value will not propagate to other scopes (though an object's properties will be manipulated by reference). Scope 1: Components.utils.import("resource://app/my_module.jsm"); bar = "foo"; alert(bar); // displays "foo" Scope 2: Components.utils.im...
... Packaging notes It's important to note that you shou...
...["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); aliasFile.initWithPath("/some/absolute/path"); var aliasURI = Services.io.newFileURI(aliasFile); resProt.setSubstitution("myalias", aliasURI); // assuming the code modules are in the alias folder itself Notes Custom modules and
XPCOM components Note that prior to Gecko 2.0 JavaScript
XPCOM components are loaded before chrome registration. This means you can't use Components.utils.import() with your own resource URL at the top level in a component source. A possible solution is moving the call to Components.utils.import() into the
XPCOM component constructor (discussion). Packaging notes It's important to note that you should not typically put your JavaScript code modules in a JAR...
Investigating leaks using DMD heap scan mode
. The build is going to be very slow, so you may need to disable some shutdown checks. First, in toolkit/components/terminator/nsTerminator.cpp, delete everything in RunWatchDog but the call to NS_SetCurrentThreadName. This will keep the watch dog from killing the browser when shut down takes multiple minutes. Secondly, you may need to comment out the call to MOZ_CRASH("NSS_Shutdown failed"); in
xpcom/build/
XPCOMInit.cpp, as this also seems to trigger when shutdown is extremely slow. You need the cycle collector analysis script find_roots.py, which can be downloaded as part of this repo on Github. Generating Logs The next step is to generate a number of log files. You need to get a shutdown CC log and a DMD log, for a single run. Definitions I'll write $objdir for the object directory for...
...ingle run. Definitions I'll write $objdir for the object directory for your Firefox DMD build, $srcdir for the top level of the Firefox source directory, and $heapgraph for the location of the heapgraph repo, and $logdir for the location you want logs to go to. $logdir should end in a path separator. For instance, ~/logs/leak/. The command you need to run Firefox will look something like this:
XPCOM_MEM_BLOAT_LOG=1 MOZ_CC_LOG_SHUTDOWN=1 MOZ_DISABLE_CONTENT_SANDBOX=t MOZ_CC_LOG_DIRECTORY=$logdir MOZ_CC_LOG_PROCESS=content MOZ_CC_LOG_THREAD=main MOZ_DMD_SHUTDOWN_LOG=$logdir MOZ_DMD_LOG_PROCESS=tab ./mach run --dmd --mode=scan Breaking this down:
XPCOM_MEM_BLOAT_LOG=1: This reports a list of the counts of every object created and destroyed and tracked by the
XPCOM leak tracking system. From...
...d directly by the child processes. MOZ_CC_LOG_DIRECTORY=$logdir: This selects the location for cycle collector logs to be saved. MOZ_CC_LOG_PROCESS=content MOZ_CC_LOG_THREAD=main: These options specify that we only want CC logs for the main thread of content processes, to make shutdown less slow. If your leak is happening in a different process or thread, change the options, which are listed in
xpcom/base/nsCycleCollector.cpp. MOZ_DMD_SHUTDOWN_LOG=$logdir: This option specifies that we want a DMD log to be taken very late in
XPCOM shutdown, and the location for that log to be saved. Like with the CC log, we want this log very late to avoid as many non-leaking things as possible. MOZ_DMD_LOG_PROCESS=tab: As with the CC, this means that we only want these logs in content processes, in order t...
...ateLoadRequest(). Fortunately, this method mostly just contains two calls to new, one for ScriptLoadRequest and one for ModuleLoadRequest. (This is where an unoptimized build comes in handy, as it would have pointed out the exact line. Unfortunately, in this particular case, the unoptimized build was so slow I wasn't getting any logs.) I then looked through the list of leaked objects generated by
XPCOM_MEM_BLOAT_LOG and saw that we were leaking a ScriptLoadRequest, so I went and looked at its class definition, where I noticed that ScriptLoadRequest had a strong reference to an element that it wasn't telling the cycle collector about, which seemed suspicious. The first thing I did to try to confirm that this was the source of the leak was pass the address of this object into the cycle collector...
SMILE
We want to start with areas that will provide the most benefit. ...
...ons of extIApplication. The library has also been implemented in Firefox ("FUEL") and in Thunderbird ("STEEL"). ...
.... ...
...ntItem extIEventListener extIEvents extIExtension extIExtensions extIPreference extIPreferenceBranch extISessionStorage smileIApplication Objects smileIBookmarkRoots smileIWindow smileIBrowserTab smileIApplication
XPCOM Although the extIApplication object is preloaded into XUL scripts, it is not preloaded into JavaScript
XPCOM code. The object needs to be accessed like any other
XPCOM service: var Application = Components.classes["@mozilla.org/smile/application;1"].getService(Components.interfaces.smileIApplication); ...
extIApplication
Method overview boolean quit() boolean restart() void getExtensions(extIExtensionsCallback aCallback) Attributes The following interfaces are available to all applications: Attribute Type Description id readonly attribute AString The id of the application. ...
... indicating whether the shutdown was successful. restart() Attempts to restart the application. It is possible for the restart to be canceled. boolean restart() Return value boolean value indicating whether the restart was successful. getExtensions(aCallback) Calls aCallback with the list of installed extensions. void getExtensions(extIExtensionsCallback aCallback) Return value none. ...
...ossible for the restart to be canceled. boolean restart() Return value boolean value indicating whether the restart was successful. getExtensions(aCallback) Calls aCallback with the list of installed extensions. void getExtensions(extIExtensionsCallback aCallback) Return value none. ...
... Return value boolean value indicating whether the restart was successful. getExtensions(aCallback) Calls aCallback with the list of installed extensions. void getExtensions(extIExtensionsCallback aCallback) Return value none.
XPCOM Although the Application object is preloaded into XUL scripts, it is not preloaded into JavaScript
XPCOM code. ...
Fun With XBL and XPConnect
Introduction This article describes an application of XBL in which a simple
XPCOM interface is made accessible to a XUL widget. The interface definition feature of XBL is used to define an interface through XPConnect to a C++ object that does auto completion. Once the regular XUL textfield widget is bound to this interface, it calls the auto complete function of the object using regular JavaScript. The basic model of interaction is as follows: Binding to the
XPCOM Object The widget holds onto an
XPCOM object that is the auto complete engine that will perform our auto complete lookups. <binding name="autocomplete" extends="xul:box"> <content> <xul:textfield class="addressingWidget"/> <xul:menupopup/> </content> <implementation> <property name="autoCompleteSession"> ...
...Components.classes['component://netscape/messenger/autocomplete&type=addrbook']. getService(Components.interfaces.nsIAutoCompleteSession); ]]> </property> So we've defined a property on the widget called autoCompleteSession. The initial value of this property evaluates to an xp-connect object. Now accesses to autoCompleteSession will return the xp-connect object. Exposing the
XPCOM Interfaces One somewhat nasty trick you need to do is to manually expose the interfaces of the
XPCOM object that you want your widget to support. All you have to do is specifically defining a method on the XBL widget which forwards the method call to the
XPCOM object. <method name="autoComplete"> <argument name="aSearchString"/> <argument name="resultListener"/> <body> ...
...ethod is just getting the auto complete session object and calling the auto complete method on it. Implementing a Widget Interface The next thing I needed to do was to implement an interface on the widget which I could then pass into the auto complete session. I wanted the auto complete session to call back into the widget with search results. ...
...ements my interface. Now I can pass the result of autoCompleteListener into methods that require an auto complete listener (like my auto complete session object). Creating the Event Handler The last part is the easy part. I wanted a handler that would kick off the auto complete search. The handler calls the auto complete method we've exposed on the widget which in turn forwards the call to the
XPCOM object, passing in our implementation of nsIAutoCompleteListener. <handlers> <handler type="keypress" keycode="vk_return" value="autoComplete(anonymousContent[0].value, this.autoCompleteListener);"/> </handlers> </implementation> </binding> Original Document Information Author(s): Scott MacGregor Last Updated Date: April 13, 2000 Copyright Information: Copyright (...
Receiving startup notifications
See The startup process for details on how this now works, if you're interested in specifics. The important thing to note is that now instead of registering with the Category Manager programmatically as was done in the past, you add lines to your chrome.manifest to let the application handle it for you. ...
...See The startup process for details on how this now works, if you're interested in specifics. The important thing to note is that now instead of registering with the Category Manager programmatically as was done in the past, you add lines to your chrome.manifest to let the application handle it for you. ...
... profile-after-change MyComponent @foobar/mycomponent;1 Important: In the past, the contract ID of the category entry started with "service," if the component was implemented as a service. This is no longer the case, so be sure to remove that when migrating existing code. Additionally, the earliest startup time notification you can receive is now profile-after-change. Your add-on will not receive
xpcom-startup or app-startup notifications. The startup process During application startup, the application's manifest is used to get a list of the components it needs to register, and those components are loaded. This gets enough of
XPCOM and the application loaded and running that the Extension Manager can then be loaded and handle installing, uninstalling, and updating any installed extensions. Once...
...ply reading their manifests, loading their components, and continuing with application startup, all without having to restart the browser. Receiving startup notifications prior to Gecko 2.0 (Firefox 4) To receive startup notifications, one needs to register with the "app-startup" category using nsICategoryManager; having done so, the component will receive these startup notifications, including:
xpcom-startup Sent when
XPCOM finishes starting up. Most application features are not yet available at this point, but
XPCOM itself is. app-startup Sent when the application has finished starting up. final-ui-startup Sent just before the first application window is displayed. Registering with the Category Manager To register with the Category Manager, simply call its nsICategoryManager.AddCategoryEntr...
Components.utils.import
See Using JavaScript code modules for more details. Note: Prior to Gecko 2.0, JavaScript code modules could only be loaded using file: or resource: URLs. Gecko 2.0 adds support for loading modules from chrome: URLs, even those inside JAR archives. ...
...ways provide a scope. In case of doubt, this is generally a good scope. return value the module's global object. use of the return value is discouraged since it grants access to the module's internal properties which are not part of its public API. import throws if it encounters an error (like a syntax error) in the file it reads. Example Components.utils.import("resource://gre/modules/
XPCOMUtils.jsm", this); Difference from mozIJSSubScriptLoader The differences from mozIJSSubScriptLoader: The behavior when importing/loading the same code from different locations: the subscript loader evaluates the specified code each time it is invoked, with the caller's global object. Components.utils.import evaluates the code of each module only once, in its own scope. For example: var ...
...ons: the subscript loader evaluates the specified code each time it is invoked, with the caller's global object. Components.utils.import evaluates the code of each module only once, in its own scope. ...
...loader evaluates the specified code each time it is invoked, with the caller's global object. Components.utils.import evaluates the code of each module only once, in its own scope. For example: var scope1 = {}, scope2 = {}; Components.utils.import("resource://gre/modules/JSON.jsm", scope1); Components.utils.import("resource://gre/modules/JSON.jsm", scope2); assert(scope2.
XPCOMUtils === scope1.
XPCOMUtils); ...returns true, whereas: var someURL = "resource://gre/modules/JSON.jsm"; var obj1 = {}, obj2 = {}; var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getService(Components.interfaces.mozIJSSubScriptLoader); loader.loadSubScript(someURL, obj1); loader.loadSubScript(someURL, obj2); assert(obj2 === obj1); ...returns false. This means Compo...
Components.utils.importGlobalProperties
cope. This function is not intended for sandboxes but for system-privileged scopes. To import these objects into a sandbox, use the wantGlobalProperties option in the Sandbox constructor. This function is passed an array of strings. Each string is the name of an object to import, and will be defined on the importing scope's global. ...
...hiddenDOMWindow is that on startup of Firefox, the hiddenDOMWindow objects cannot be accessed until it is fully loaded. Therefore readyState must be checked, if it is not complete, then a load listener must be attached. Once readyState is complete then the objects can be used. For example this is how to ues the File object. ...
...irefox, the hiddenDOMWindow objects cannot be accessed until it is fully loaded. Therefore readyState must be checked, if it is not complete, then a load listener must be attached. Once readyState is complete then the objects can be used. For example this is how to ues the File object. ...
...n a load listener must be attached. Once readyState is complete then the objects can be used. For example this is how to ues the File object. ...
nsIDocShell
void fireUnloadNotification(); Native code only! Obsolete since Gecko 1.8 nsISimpleEnumerator getDocShellEnumerator(in long aItemType, in long aDirection); nsIDOMStorage getSessionStorageForPrincipal(in nsIPrincipal principal, in DOMStrin...
...nt viewer. void createAboutBlankContentViewer( in nsIPrincipal aPrincipal ); Parameters aPrincipal The principal to use for the new document. createLoadInfo() Creates a DocShellLoadInfo object that you can manipulate and then pass to loadURI(). void createLoadInfo( out nsIDocShellLoadInfo loadInfo ); Parameters loadInfo The new nsIDocShellLoadInfo object. Violates the
XPCOM interface guidelines DetachEditorFromWindow() Disconnects this docshell's editor from its window, and stores the editor data in the open document's session history entry. This should be called only during page transitions. void DetachEditorFromWindow(); Parameters None. finishRestore() Finish firing WebProgressListener notifications and DOM events for restoring a page presentation. This shou...
... some of those might not be allowed. Use at your own risk. firstParty true if this is the master top-level document. prepareForNewContentModel() Reset state to a new content model within the current document and the document viewer. Called by the document before initiating an out of band document.write(). void prepareForNewContentModel(); Parameters None. resumeRefreshURIs() Restart the
XPCOM timers for each meta-refresh URI in this docshell, and this docshell's children, recursively. If the timers are already running, this has no effect. void resumeRefreshURIs(); Parameters None. Native code only!setChildOffset Set the offset of this child in its container. void setChildOffset( in unsigned long offset ); Parameters offset The offset of this nsIDocShell within its parent...
... The offset of this nsIDocShell within its parent. Used to restore session history for frames. setCurrentURI() For editors and suchlike who wish to change the URI associated with the document. Note if you want to get the current URI, use the read-only property on nsIWebNavigation. void setCurrentURI( in nsIURI aURI ); Parameters aURI The URI to load. suspendRefreshURIs() Cancel the
XPCOM timers for each meta-refresh URI in this docshell, and this docshell's children, recursively. The meta-refresh timers can be restarted using resumeRefreshURIs(). If the timers are already suspended, this has no effect. void suspendRefreshURIs(); Parameters None. tabToTreeOwner() Tells the docshell to offer focus to its tree owner. This is currently only necessary for embedding chrome. void tabTo...
nsIErrorService
xpcom/base/nsIErrorService.idlScriptable This is a service that allows nsresult codes to be mapped to string bundles that can be used to look up error messages. String bundle keys can also be mapped. ...
...
xpcom/base/nsIErrorService.idlScriptable This is a service that allows nsresult codes to be mapped to string bundles that can be used to look up error messages. String bundle keys can also be mapped. ...
...n value The key to use to retrieve the error string from the nsresult's module's string bundle. registerErrorStringBundle() Registers a string bundle URL for an error module. void registerErrorStringBundle( in short errorModule, in string stringBundleURL ); Parameters errorModule The module for which the string bundle is to be registered. Should be one of the modules listed in
xpcom/base/nsError.h, such as NS_ERROR_MODULE_STORAGE. stringBundleURL The URL of the string bundle to register for the module. registerErrorStringBundleKey() Registers a key in a string bundle for an nsresult error code. void registerErrorStringBundleKey( in nsresult error, in string stringBundleKey ); Parameters error The nsresult for which the string bundle key is ...
...undleKey The key that should be used to retrieve the error string from string bundle for the given nsresult. unregisterErrorStringBundle() Unregisters a string bundle URL for an error module. void unregisterErrorStringBundle( in short errorModule ); Parameters errorModule The module for which the string bundle is to be unregistered. Should be one of the modules listed in
xpcom/base/nsError.h, such as NS_ERROR_MODULE_STORAGE. unregisterErrorStringBundleKey() Unregisters a key in a string bundle for an nsresult error code. void unregisterErrorStringBundleKey( in nsresult error ); Parameters error The nsresult for which the string bundle key is to be unregistered. ...
nsIProperties
Inherits from: nsISupports Last changed in Gecko 1.2 Implemented by: @mozilla.org/file/directory_service;1. To get an instance, use: var properties = Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIProperties); Method overview void get(in string prop, in nsIIDRef iid, [iid_is(iid),retval] out nsQIResult result); void getKeys(out PRUint32 count, [array, size_is(count), retval] out string keys); boolean has(in string prop); void set(in string prop, in nsISupports value); void undefine(in string prop); Methods get() Gets the
XPCOM object associated with a particular name. ...
...void get( in string prop, in nsIIDRef iid, [iid_is(iid),retval] out nsQIResult result ); Parameters prop The property name. iid The desired interface. result The resulting object instance. Exceptions thrown NS_ERROR_FAILURE If the property does not exist. NS_ERROR_NO_INTERFACE If the property exists, but does not support the requested interface.
...iid, [iid_is(iid),retval] out nsQIResult result ); Parameters prop The property name. iid The desired interface. result The resulting object instance. Exceptions thrown NS_ERROR_FAILURE If the property does not exist. NS_ERROR_NO_INTERFACE If the property exists, but does not support the requested interface. getKeys() Returns an array of property names. nsMemory.h defines the macro NS_FREE_
XPCOM_ALLOCATED_POINTER_ARRAY, which can be used to free aKeys when it is no longer needed. void getKeys( out PRUint32 count, [array, size_is(count), retval] out string keys ); Parameters count The length of the result array. keys The resulting array of keys. has() Tests if a property exists. boolean has( in string prop ); Parameters prop The property name. Return value true if the property...
... it is no longer needed. void getKeys( out PRUint32 count, [array, size_is(count), retval] out string keys ); Parameters count The length of the result array. keys The resulting array of keys. has() Tests if a property exists. boolean has( in string prop ); Parameters prop The property name. Return value true if the property exists, false if the property does not exist. set() Sets the
XPCOM object associated with a particular name. void set( in string prop, in nsISupports value ); Parameters prop The property name. value The
XPCOM object value to associate with prop. undefine() Undefines a property. void undefine( in string prop ); Parameters prop The property name. Remarks This interface was frozen for Gecko 1.2. See bug 162114 for details. From Gecko 2.0 interfaces are...
Using nsIDirectoryService
This implementation will allow you to Get(), Set(), Define(), and Undefine() nsIFile. Getting a location: Most developers need to find where a file or directory is located. With nsDirectoryService, there are two steps involved. First, you must know what the string key (or property) is that refers to this locations. Header files containing known keys are listed in the Known Locations section of this document. Bear in mind that this list is not static. Components can add and remove locations at their will. ...
...ple, in SeaMonkey, the profile service is a provider for locations that are relative to the current profile. The caller asking for the file location, of course, doesn't need to know who the providers are. As a caller of the service, you never deal with the providers, only the service. Defined Locations The nsIProperties keywords that you will use to get locations are defined in two places. OS and
XPCOM Level nsDirectoryServiceDefs.h These locations are provided by
XPCOM, are constant with the system, and and should not need customization. Although you will not customize these locations, you may need to tell
XPCOM where its /bin directory is. This is done by passing a directory to NS_Init
XPCOM or, for embedding, as the first parameter to NS_InitEmbedding. The location of the Components folder an...
...ATH environment variables, you will need to set one of these paths to the /bin directory. Application Level nsAppDirectoryServiceDefs.h The first group listed is for locations that are relative to the application: for instance, the name and location of the chrome folder, or the default location of user profiles. The nsIDirectoryServiceProvider which normally provides these locations is at mozilla/
xpcom/io/. This provider is installed by SeaMonkey after initializing
XPCOM. It is also installed by default by NS_InitEmbedding. The second group listed is for locations which are relative to the current user profile. In SeaMonkey, the profile service is an nsIDirectoryServiceProvider and it provides these locations. There are some cases in embedding in which distinct user profiles are not needed; how...
...e a component - it can be a static lib, a source file in your project - whatever. Just construct it, pass it to NS_InitEmbedding, and it will be installed. If you are not using NS_InitEmbedding, you will have to construct it and register it yourself using nsIDirectoryService.registerProvider(). If you are registering it yourself it is very important to register it immediately after calling NS_Init
XPCOM. There are things in the startup process that need these locations at a very early point - even before registering components. If you want to use mpfilelocprovider, or something like it, to provide one fixed profile, just construct it and call its Initialize method - it will register itself. Again, if you do this, do not initialize the profile service - it's either one or the other. Related Pages...
Using the clipboard
hort string to the clipboard. This method only works to put strings on the clipboard. For other types of data, such as URLs or images, you will need to use a more complex method. A component @mozilla.org/widget/clipboard;1 and an interface nsIClipboard provide general access to the system clipboard. You can use them to copy and paste any type of data from your application to the clipboard. ...
...This is needed because you can put anything on the clipboard from text to images. Create a transferring object. This object can be the component @mozilla.org/widget/transferable;1 which implements the interface nsITransferable. ...
...clipboard and doesn't understand HTML, it can use the plain text version. If it does understand HTML, it can grab that version. The transferring object will hold the clipboard contents until the application has decided what it needs. This allows the clipboard to be used by another application right away. Let's break down the steps needed to copy data to the clipboard. First, we need to create an
XPCOM object to wrap what we want to copy. We'll assume that we want to copy some text. We will use the interface nsISupportsString which can be used to represent strings (specifically, Unicode strings). The following boilerplate utility functions will be used in all later code examples. // Import the Services module for future use, if we're not in // a browser window where it's already loaded. Compo...
...ble flavor is possible. If you originally copied data of multiple flavors onto the clipboard, you can retrieve the data in the best format necessary. For example, a textbox would accept "text/unicode" (or "text/plain") while a Composer window might accept HTML and image data. The variable str now holds the data from the clipboard. We need to convert the data back into a JavaScript string from an
XPCOM object. The code below can be used for this purpose: if (str) { var pastetext = str.value.QueryInterface(Ci.nsISupportsString).data; } Because the data from the transferable is an nsISupportsString, we need to convert it into a JavaScript string. The property value of the object filled in by getTransferData, which is str in this case, provides the actual value of the object. We assign the st...
Mozilla
han any secondary replacements of KDEwallet. Creating a spell check dictionary add-on This page describes how to package a Hunspell spell check dictionary as a Firefox add-on, or how to update your existing add-on, so that it can be installed, uninstalled and updated without a restart. Creating JavaScript callbacks in components
XPCOM components use IDL to create interfaces. These interfaces are used to manipulate the component in C++ and JavaScript. A common pattern used with interfaces to create a bi-directional communication between two groups of code is the observer (or listener) pattern. Basically, the component defines an observer (or listener) interface which is implemented by some external code ...
...ieve the same visual effect. Reftest will then compare them and verify whether they produce the same bitmap. Creating Sandboxed HTTP Connections Starting with Gecko 1.8.1 (Firefox 2), it is possible to create sandboxed HTTP connections which don't affect the user's cookies. This article will cover the basics of doing HTTP connections from
XPCOM JavaScript, and should easily translate to C++
XPCOM. Debugging Debugging a project as large as Mozilla can be a daunting task. Fortunately, over the years, Mozilla developers have come up with not just technologies and features to help you debug code, but have devised tips and techniques that can help too. Also available are assorted too...
...ack and forth to native code written in C. C++ support is possible through vtable pointers see Using COM from js-ctypes. For a discussion on extended C++ support see bug 505907. Other work made possible by js-ctypes is JNI, this is elaborated on in the JNI.jsm section and not the js-ctypes section due to the JSM abstracting away all of the js-ctypes. Unlike binary
XPCOM components, it allows developers to ship a single binary for use with multiple versions of Firefox. Localization at Mozilla Localization (L10n) is the process of translating software user interfaces from one language to another and adapting it to suit a foreign culture. These resources are for anyone with an interest in the technical ...
... Mozilla external string guide The Mozilla codebase used to have a notion of "external" strings, which were the string classes visible to code outside of the Mozilla codebase (Extensions, XULRunner applications, and embedders). These classes were removed a long time ago. The only remaining string classes are the "internal" ones, which are documented
XPCOM Guide Internal strings. Mozilla Framework Based on Templates (MFBT) The Mozilla Framework Based on Templates ("mfbt") is the central repository for macros, functions, and data structures used throughout Mozilla code, including in the JavaScript engine. Mozilla MathML Project The Mozilla MathML project is Mozilla's project to build and...
Bookmarks - Archive of obsolete content
.getFolderIdForItem() method. var parentFolderId = bmsvc.getFolderIdForItem(newBkmkId); Observing changes to bookmarks and tags To set up an observer to listen for changes related to bookmarks, you will need to create an nsINavBookmarkObserver object and use the nsINavBookmarksService.addObserver() and nsINavBookmarksService.removeObserver() methods. Note that this example takes advantage of
XPCOMUtils to generate the nsISupports.QueryInterface() method. // An nsINavBookmarkObserver var myExt_bookmarkListener = { onBeginUpdateBatch: function() {}, onEndUpdateBatch: function() {}, onItemAdded: function(aItemId, aFolder, aIndex) {}, onItemRemoved: function(aItemId, aFolder, aIndex) {}, onItemChanged: function(aBookmarkId, aProperty, aIsAnnotationProperty, aValue) { MyExtension...
...tion() {}, onItemAdded: function(aItemId, aFolder, aIndex) {}, onItemRemoved: function(aItemId, aFolder, aIndex) {}, onItemChanged: function(aBookmarkId, aProperty, aIsAnnotationProperty, aValue) { MyExtension.doSomething(); }, onItemVisited: function(aBookmarkId, aVisitID, time) {}, onItemMoved: function(aItemId, aOldParent, aOldIndex, aNewParent, aNewIndex) {}, QueryInterface:
XPCOMUtils.generateQI([Components.interfaces.nsINavBookmarkObserver]) }; // An extension var MyExtension = { // This function is called when my add-on is loaded onLoad: function() { bmsvc.addObserver(myExt_bookmarkListener, false); }, // This function is called when my add-on is unloaded onUnLoad: function() { bmsvc.removeObserver(myExt_bookmarkListener); }, doSomething: function(...
...nction is called when my add-on is loaded onLoad: function() { bmsvc.addObserver(myExt_bookmarkListener, false); }, // This function is called when my add-on is unloaded onUnLoad: function() { bmsvc.removeObserver(myExt_bookmarkListener); }, doSomething: function() { alert("Did something."); } }; See also nsINavBookmarksService nsINavBookmarkObserver Places Using
XPCOM without chrome - Bookmark Observer ...
Finding window handles - Archive of obsolete content
content windows (in tabs) do not have their own HWNDs. Typically the top level browser window HWND has no children, although if there are windowed plugins (such as Flash) visible in the window, they will have HWNDs whose parent is the top level browser window HWND. Here is some simple code that can get access to Mozilla window handles. This code can be used from external application or from an
XPCOM component within an extension. Finding the content window handle HWND hContent = 0; // first we need to find the main browser window HWND hFF = ::FindWindowEx(0, 0, "MozillaUIWindowClass", 0); if (hFF) { // next we step down through a fixed structure HWND hTemp; hTemp = ::FindWindowEx(hFF, 0, "MozillaWindowClass", 0); hTemp = ::FindWindowEx(hTemp, 0, "MozillaWindowClass", 0...
...ctypes.unsigned_int : ctypes.unsigned_long; var XID = CARD32; var gdk = ctypes.open('libgdk-x11-2.0.so.0'); var gdk_x11_drawable_get_xid = gdk.declare('gdk_x11_drawable_get_xid', ctypes.default_abi, XID, GdkDrawable.ptr); var GDKWindowPtrString = baseWindow.nativeHandle; var GdkWinPtr = GdkWindow.ptr(ctypes.UInt64(GDKWindowPtrString)); var GdkDrawPtr = ctypes.cast(GdkWinPtr, GdkDrawable.
...tring = baseWindow.nativeHandle; Components.utils.import('resource://gre/modules/ctypes.jsm'); var gdk = ctypes.open('libgdk-x11-2.0.so.0'); var x11 = ctypes.open('libX11.so.6'); // types let guint32 = ctypes.uint32_t; let GdkWindow = ctypes.StructType('GdkWindow'); let GdkDrawable = ctypes.StructType('GdkDrawable'); let CARD32; if (/^(Alpha|hppa|ia64|ppc64|s390|x86_64)-/.test(Services.appinfo.
XPCOMABI)) { CARD32 = ctypes.unsigned_int; } else { CARD32 = ctypes.unsigned_long; } let XID = CARD32; //https://developer.gnome.org/gdk2/stable/gdk2-X-Window-System-Interaction.html#gdk-x11-drawable-get-xid var gdk_x11_drawable_get_xid = gdk.declare('gdk_x11_drawable_get_xid', ctypes.default_abi, XID, GdkDrawable.ptr); var browserWindow_madeIntoGdkWinPtr = GdkWindow.ptr(ctypes.UInt64(GDKWi...
Preferences - Archive of obsolete content
nformation here applies to the Mozilla Suite, Firefox, Thunderbird, and possibly other Mozilla-based applications. For more details on preferences in Mozilla, see Preferences System. If you haven't yet, read other documents about Mozilla preferences on MDN (links below in Resources section). Note: This article doesn't cover all available methods for manipulating preferences; please refer to the
XPCOM reference pages listed in Resources section for the complete list of methods. The interfaces dealing with preferences are fairly well documented, so using the methods not mentioned here should be straightforward.
XPCOM interfaces for preferences system Mozilla exposes its preferences system through a few
XPCOM interfaces. Look in the Resources section below for the link to a list of preferences...
...To get an nsIPrefBranch, either QueryInterface() the pref service (that will give you the root branch) or call nsIPrefService.getBranch() to get a sub-branch. ...
...eference and has the old value and along with the new value of the preference. It also uses a technique so you can just do prefs.preferenceName.setval('blah') instead of having to branch.setCharPref etc. ...
How to convert an overlay extension to restartless - Archive of obsolete content
This article is a step-by-step tutorial on how to convert an old overlay-based extension into a restartless (bootstrapped) extension that is also extractionless. Requirements First off, what kind of add-on are we talking about here? Well, XUL overlays and windows, JSM files, chrome & resource mappings with localization, default preferences, but no
XPCOM components of your own. Some of that will have to be replaced and the rest will need to be loaded differently. Next, what's the minimum version of Firefox we should require (preferably an ESR)? This guide targets Firefox 17 ESR or later (or anything else Gecko 17+, such as SeaMonkey 2.14+). This is two ESRs back (as of this writing), which should be plenty. Using the current Firefox ESR, stable version, or Nightly is generally a better ide...
... for whatever reason. String changes seem to be fine, however the addition or removal of strings can sometimes produce this error. It's not reliably reproducible, but it does happen. Yes, this is a pain in the ass. The suggestion that seems to work is to use a hack to bypass the string bundle cache. ...
... it does happen. Yes, this is a pain in the ass. The suggestion that seems to work is to use a hack to bypass the string bundle cache. You should still be caching a reference to your string bundle on add-on startup, preferably using
XPCOMUtils.jsm to lazily load the file. For example: Components.utils.import("resource://gre/modules/Services.jsm"); Components.utils.import("resource://gre/modules/
XPCOMUtils.jsm");
XPCOMUtils.defineLazyGetter(this, "strings", function() { return loadPropertiesFile("chrome://myAddon/locale/mystrings.properties"); }); function loadPropertiesFile(path) { /* HACK: The string bundle cache is cleared on addon shutdown, however it doesn't appear to do so reliably. Errors can erratically happen on next load of the same file in certain instances. (at minim...
Install Manifests - Archive of obsolete content
in their manifests, you can set the extensions.strictCompatibility preference to true. Note: Starting in Gecko 11.0, applications such as Firefox will assume add-ons that have not been updated in a very long time are no longer compatible by default. targetPlatform A string specifying a platform that the add-on supports. It contains either the value of OS_TARGET alone or combined with TARGET_
XPCOM_ABI, separated by an underscore (_). You can specify multiple targetPlatform properties per manifest. If any value matches the application's build parameters, it will be installed; if not, the user will get an appropriate error message. Examples <em:targetPlatform>WINNT_x86-msvc</em:targetPlatform> <em:targetPlatform>Linux</em:targetPlatform> <em:targetPlatform>Darwin_ppc-gcc3</em:targetPlat...
...> unpack A true or false value that tells the application whether the extension requires its files be unpacked into a directory in order to work or whether the extension can be loaded direct from the XPI. In versions before Gecko 2.0 all extensions were unpacked, in Gecko 2.0 and later the default is to not unpack. If an extension includes the following then it must request unpacking: Binary
XPCOM components Plugins Search plugins DLLs loaded with ctypes Dictionaries Window icons Examples <Description about="urn:mozilla:install-manifest"> <em:id>extension@mysite.com</em:id> <em:unpack>true</em:unpack> ... </Description> updateKey To ensure the security of update rdf data that is retrieved over plain HTTP you must use a digital signature to verify the contents of the d...
...klisted or softblocked. %APP_ID% The id of the current application %APP_VERSION% The version of the application to check for updates for %CURRENT_APP_VERSION% The version of the current application %APP_OS% The value of OS_TARGET from the Firefox build system, identifying the operating system being used. %APP_ABI% The value of the TARGET_
XPCOM_ABI value from the Firefox build system, identifying the compiler/architecture combination used to compile the current application. %APP_LOCALE% The current application's locale. %UPDATE_TYPE% UPDATE_TYPE_COMPATIBILITY(32), UPDATE_TYPE_NEWVERSION(64) %COMPATIBILITY_MODE% related to default to compatible, values could be normal, ignore or strict. Examples...
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
at all). For errors about undeclared do_CreateInstance: #include "nsComponentManagerUtils.h" For errors about undeclared do_GetService: #include "nsServiceManagerUtils.h" For errors about undeclared NS_GetSpecialDirectory: #include "nsDirectoryServiceUtils.h" Utility Classes Some utility classes could previously be created with NS_New* utility functions. ...
...Don't use it in new code. Use nsIArray instead. ...
...The nsMsgUtils.h header For developing core Mail/News code, the nsMsgUtils.h header is being enhanced to fill in some of the gaps caused by the differences between the internal and external APIs. These enhancements make it easier to write code that will transparently compile using either API. The list of enhancements fall in to three categories. Changes to internal APIs to make them compati...
Structure of an installable bundle - Archive of obsolete content
p.js The bootstrap script for extensions not requiring a restart (those with <em:bootstrap>true</em:bootstrap> in their install.rdf). Note that other files and directories (e.g. chrome.manifest, components, defaults) in bootstrapped extensions are not processed by a supporting application. ...
...facilitate the first case, the extension/app loader has special sub-directories specifically for platform-specific files (starting with Toolkit/Gecko 1.8, Firefox/Thunderbird 1.5). The platform string is defined during the toolkit build process to a value unique for the combination of operating system, processor architecture and compiler. The format of the platform string is: {OS_TARGET}_{TARGET_
XPCOM_ABI} All of the files which are loaded from the main extension directory are loaded from the subdirectory /platform/{platform string} if it exists. For example, if a plugin vendor wanted to make a plugin available for consumer computers running Linux(of the form: /platform/Linux*/), Macintosh(of the form: /platform/Darwin*/), and Windows(of the form: /platform/WIN*/), it would provide the fo...
...When default preferences are defined in several directories, the ones loaded later overwrite the earlier ones. Official references for toolkit API Structure of an Installable Bundle: describes the common structure of installable bundles, including extensions, themes, and XULRunner applications Extension Packaging: specific information about how to package extensions Them...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
It works by providing an object which implements the event handlers. All you have to do is write some simpler functions which work with the data being dragged. ...
...event,textObserver)" ondragdrop="nsDragAndDrop.drop(event,textObserver)" /> As mentioned earlier, there is nothing special that happens during a dragenter event, so you can just write that yourself. The functions are implemented by the nsDragAndDrop object, which is declared in the file nsDragAndDrop.js, which was included in one of the script tags. They handle the event, handle the
XPCOM interfaces and pass a simpler data structure to functions of the observer object. The observer is an object that you declare yourself. In the above examples, this observer is stored in the buttonObserver and textObserver variables. The observer is declared in a script which you would include in the XUL file using the script tag. The observer is an object which may have a number of properties, eac...
...unction. We'll allow only one flavour here, that for a string. var textObserver = { getSupportedFlavours : function () { var flavours = new FlavourSet(); flavours.appendFlavour("text/unicode"); return flavours; } } The flavours list contains only one flavour, which is 'text/unicode'. The FlavourSet object can be used to hold a list of flavours. In some cases, you must provide the
XPCOM interface as well. For example, for files: var textObserver = { getSupportedFlavours : function () { var flavours = new FlavourSet(); flavours.appendFlavour("application/x-moz-file","nsIFile"); flavours.appendFlavour("text/unicode"); return flavours; } } The onDragOver function defines what happens when an object is dragged over. You might use it to change the appearance of t...
Embedding FAQ - Archive of obsolete content
code examples found. However, there is a stripped down, uncommented code with eclipse libraries in this thread. ...
...You can find a better quality answer repeated and with an example in this newsgroup thread. ...
...You can find a better quality answer repeated and with an example in this newsgroup thread. ...
PyDOM - Archive of obsolete content
The globals are 'bound' to the global object (i.e., the window), instead of to a module's __dict__ as you expect in the Python world. ...
..."> block does. Almost Python code can not be secured - so it will only run from trusted sources. This means you can only have Python code in chrome. Content loaded from anywhere other than a chrome:// URL can not host Python. ...
...Python code can not be secured - so it will only run from trusted sources. This means you can only have Python code in chrome. Content loaded from anywhere other than a chrome:// URL can not host Python. ...
Mac stub installer - Archive of obsolete content
rior project. How we get setup to debug the XPInstall engine from the mac installer? Once you have the mac installer built and ready to debug you may want to debug the XPInstall engine in the context of the installer rather than in the context of the browser. ...
...c installer? Once you have the mac installer built and ready to debug you may want to debug the XPInstall engine in the context of the installer rather than in the context of the browser. ...
...and step into xpistub and eventually the XPInstall engine will load including symbols so you can set a break point in the XPInstall engine itself. How do I add an installer package to the Mac installer? Adding a package involves a few steps: Add a section named for your <component> to the packages-mac manifest that describes which files from dist belong to which module. For example, see the
xpcom section that lists all the shared libraries as seen in dist. These are eventually zipped with the directory structure preserved. Read the top of the packages-mac file for it's simple syntax and semantics. Add an <component>.jst install script template file (the jst extension stands for javascript template indicating this is a template for the final install.js for the <component>.xpi. Checkin the...
Using nsIXULAppInfo - Archive of obsolete content
older applications, such as Firefox and Thunderbird 1.0, do not support it. You'll need to have additional code for those older versions. Getting nsIXULAppInfo To get a component implementing nsIXULAppInfo use this code: var appInfo = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULAppInfo); (For explanation see this Creating
XPCOM article.) Getting application information After you obtained the app info component, you can read its properties to get the application's ID, human-readable name, version, platform version, etc. For complete list of nsIXULAppInfo's properties, please see nsIXULAppInfo interface description. ID You can tell which application you're running under using the nsIXULAppInfo.ID property. const FIRE...
...lication, and the former can be useful if you only support official releases, and to distinguish between branch and trunk builds. ...
....getService(Components.interfaces.nsIXULAppInfo); var platformVer = appInfo.platformVersion; var platformBuildID = appInfo.platformBuildID; Getting nsIXULAppInfo in xpcshell tests In Firefox 21, a testing module was added that provides access to app info during the execution of xpcshell tests. See Bug 809920, and in summary: // Work around the fact that xpcshell doesn't have a proper app-info
XPCOM object. Cu.import("resource://testing-common/AppInfo.jsm"); updateAppInfo(); Older versions As stated above, older Mozilla 1.7-based applications do not support nsIXULAppInfo. You'll have to write additional code if you choose to support those versions. For example, Firefox and Thunderbird 1.0 stored their ID in the app.id preference (and their version in app.version), so you could use code li...
2006-09-06 - Archive of obsolete content
Summary: mozilla.dev.tech.
xpcom - Oct 06-13, 2006 Announcements None during this week. Discussions Windows gecko-SDK and g++ components Discussion on the problems and possible solutions running cygwin/g++ compiled
XPCOM components with Windows-based Gecko-SDK/XULRunner DLL/EXEs. Threading in
XPCOM Rules on threading in
XPCOM or to Firefox extensions. ...
... Summary: mozilla.dev.tech.
xpcom - Oct 06-13, 2006 Announcements None during this week. Discussions Windows gecko-SDK and g++ components Discussion on the problems and possible solutions running cygwin/g++ compiled
XPCOM components with Windows-based Gecko-SDK/XULRunner DLL/EXEs. Threading in
XPCOM Rules on threading in
XPCOM or to Firefox extensions. ...
...- Oct 06-13, 2006 Announcements None during this week. Discussions Windows gecko-SDK and g++ components Discussion on the problems and possible solutions running cygwin/g++ compiled
XPCOM components with Windows-based Gecko-SDK/XULRunner DLL/EXEs. Threading in
XPCOM Rules on threading in
XPCOM or to Firefox extensions. How to build
xpcom component on Mac OS X A tutorial on how to build
xpcom component on Mac OS X Firefox crashes when calling a function provided by a .so library A solution to the problem loading a shared library when using
xpcom Firefoxes crashes while getting url in
XPCOM Solutions to resolve the problem of the firefox crash when trying to get the path and the prePath of the url of the current page in
XPCOM Meetings None during this week. ...
Archive of obsolete content
and can be incorporated into other programs. Mozilla release FAQ This document may be distributed and modified freely. No guarantee of factuality in this FAQ is made, and it is maintained by Pat Gunn, who is not affiliated with Netscape. Various other people have contributed to this FAQ. ...
...We leverage some of these ideas to help you make your Netscape Communicator 4.x plugins exposed to JavaScript in Mozilla based browsers. ...
...We leverage some of these ideas to help you make your Netscape Communicator 4.x plugins exposed to JavaScript in Mozilla based browsers. Plugins For more information about plugin roadmap, see non-archived plugin information. ...
Choosing the right memory allocator
There are a lot of different memory allocators in the Mozilla source tree. This article looks over some of them and tries to sort out which should be used under what circumstances. Allocating memory in
XPCOM These are general purpose memory-management routines that you should use unless your code falls into one of the other categories below. Use these if you link against
XPCOM or
XPCOM Glue; this includes extensions with binary components. See the
XPCOM string guide for additional information. NS_Alloc() == nsIMemory::alloc() NS_Realloc() == nsIMemory::realloc() NS_Free() == nsIMemory::free() nsMemory::Clone() (note: not part of nsIMemory) See Infallible memory allocation for information about how to allocate memory infallibly; that is, how to use memory allocators that will o...
... additional information. NS_Alloc() == nsIMemory::alloc() NS_Realloc() == nsIMemory::realloc() NS_Free() == nsIMemory::free() nsMemory::Clone() (note: not part of nsIMemory) See Infallible memory allocation for information about how to allocate memory infallibly; that is, how to use memory allocators that will only return valid memory buffers, and never return null. Allocating strings in
XPCOM code See "Callee-allocated Parameters" in the
XPCOM Strings guide; use ToNewCString() or ToNewUnicode() to allocate strings that will be passed out. These methods convert ns*String to nsIMemory allocated, unowned [PRUni]char* buffers. Do not use nsCRT::strdup for returning values from an
XPCOM object, as that uses a different allocator. NSPR memory allocators You should only use the NSPR allo...
... ...
Interface development guide
If you're going to be changing an interface, be sure to read these first! Commenting IDL for better documentation A guide explaining how to properly comment your interface's IDL in order to ensure that not only can others understand your interface, but to ensure that the documentation here on MDC is as accurate as possible. Community View Mozilla embedding forums... ...
...If you're going to be changing an interface, be sure to read these first! Commenting IDL for better documentation A guide explaining how to properly comment your interface's IDL in order to ensure that not only can others understand your interface, but to ensure that the documentation here on MDC is as accurate as possible. Community View Mozilla embedding forums... ...
... sure to read these first! ...
Gecko SDK
The Gecko SDK, also known as the XULRunner SDK, is a set of XPIDL files, headers and tools to develop
XPCOM components which can then in turn e.g. be accessed from XUL using JavaScript. Note that in order to develop such components, you do not need the full sources of e.g. Firefox, since you do not access parts of the front end from within a component. Furthermore, since a component contains basic functionality, it is intended to run with every product of the Mozilla platform. Therefore it makes no sense to use a particular product to build general functionality. That's the reason why the Gecko SDK was devised. Do not confuse the Gecko/XULRunner SDK with XULRunner itself. ...
...more, since a component contains basic functionality, it is intended to run with every product of the Mozilla platform. Therefore it makes no sense to use a particular product to build general functionality. That's the reason why the Gecko SDK was devised. Do not confuse the Gecko/XULRunner SDK with XULRunner itself. The Gecko SDK is a collection of header files and tools used to develop general
XPCOM components which add functionality to the existing platform, whereas XULRunner is a framework which can be used to run standalone or embedded applications based on the Mozilla framework. The Gecko SDK contains all of the necessary tools and headers for making scriptable NPAPI plugins including the xpidl compiler/linker and the latest npapi.h. Get the SDK Updates There is no need to download o...
...XULRunner build process, which is why it's sometimes called the XULRunner SDK). See the Build Documentation for complete details. After the XULRunner build is complete running make sdk from your object directory will create a package of the sdk in dist. Contents of the SDK The SDK contains the following: 1.9.2 IDL files for frozen interfaces (under idl/) Header files for frozen interfaces,
XPCOM functions, and NSPR functions (under include/) Import libraries or shared libraries (under lib/) Static utility libraries (under lib/) Various tools (under bin/) For more information about safely linking
XPCOM components using the
XPCOM "glue" library, see
XPCOM Glue. Using the Mozilla Build System with the SDK It's possible to use the Mozilla Build System with the SDK. This can be done by...
Manipulating bookmarks using Places
.getFolderIdForItem() method. var parentFolderId = bmsvc.getFolderIdForItem(newBkmkId); Observing changes to bookmarks and tags To set up an observer to listen for changes related to bookmarks, you will need to create an nsINavBookmarkObserver object and use the nsINavBookmarksService.addObserver() and nsINavBookmarksService.removeObserver() methods. Note that this example takes advantage of
XPCOMUtils to generate the nsISupports.QueryInterface() method. // An nsINavBookmarkObserver var myExt_bookmarkListener = { onBeginUpdateBatch: function() {}, onEndUpdateBatch: function() {}, onItemAdded: function(aItemId, aFolder, aIndex) {}, onItemRemoved: function(aItemId, aFolder, aIndex) {}, onItemChanged: function(aBookmarkId, aProperty, aIsAnnotationProperty, aValue) { MyExtension...
...tion() {}, onItemAdded: function(aItemId, aFolder, aIndex) {}, onItemRemoved: function(aItemId, aFolder, aIndex) {}, onItemChanged: function(aBookmarkId, aProperty, aIsAnnotationProperty, aValue) { MyExtension.doSomething(); }, onItemVisited: function(aBookmarkId, aVisitID, time) {}, onItemMoved: function(aItemId, aOldParent, aOldIndex, aNewParent, aNewIndex) {}, QueryInterface:
XPCOMUtils.generateQI([Components.interfaces.nsINavBookmarkObserver]) }; // An extension var MyExtension = { // This function is called when my add-on is loaded onLoad: function() { bmsvc.addObserver(myExt_bookmarkListener, false); }, // This function is called when my add-on is unloaded onUnLoad: function() { bmsvc.removeObserver(myExt_bookmarkListener); }, doSomething: function(...
...nction is called when my add-on is loaded onLoad: function() { bmsvc.addObserver(myExt_bookmarkListener, false); }, // This function is called when my add-on is unloaded onUnLoad: function() { bmsvc.removeObserver(myExt_bookmarkListener); }, doSomething: function() { alert("Did something."); } }; See also nsINavBookmarksService nsINavBookmarkObserver Places Using
XPCOM without chrome - Bookmark Observer ...
FUEL
FUEL is deprecated as of Firefox 40 and removed as of Firefox 47. Consider using the Add-ons SDK instead FUEL is a JavaScript library designed to help developers build extensions using terminology and interfaces that are familiar to them. FUEL is new in Firefox 3. FUEL is about making it easier for extension developers to be productive, by minimizing some of the
XPCOM formality and adding some "modern" JavaScript ideas. We want to start with areas that will provide the most benefit. FUEL has a fuelIApplication interface that implements all the functions of extIApplication. The library has also been implemented in Thunderbird ("STEEL") and in SeaMonkey ("SMILE"). Objects extIApplication Objects extIApplication extIConsole extIEventItem extIEventListener extIEvents extIEx...
...derbird ("STEEL") and in SeaMonkey ("SMILE"). ...
... extIEventItem extIEventListener extIEvents extIExtension extIExtensions extIPreference extIPreferenceBranch extISessionStorage fuelIApplication Objects fuelIAnnotations fuelIApplication fuelIBookmark fuelIBookmarkFolder fuelIBookmarkRoots fuelIBrowserTab fuelIWindow
XPCOM Although the FUEL Application object is preloaded into XUL scripts, it is not preloaded into JavaScript
XPCOM code. The object needs to be accessed like any other
XPCOM service: var Application = Components.classes["@mozilla.org/fuel/application;1"].getService(Components.interfaces.fuelIApplication); ...
Bundling multiple binary components
The more likely case is that the component uses "unfrozen" interfaces and those interfaces can change between Gecko versions. This can create a difficult situation for extension developers trying to support multiple Gecko versions (Firefox 2 and 3, for example). ...
...The more likely case is that the component uses "unfrozen" interfaces and those interfaces can change between Gecko versions. This can create a difficult situation for extension developers trying to support multiple Gecko versions (Firefox 2 and 3, for example). ...
...ally, NSPR has portable versions of those features that work across platforms. This approach uses only one binary for each platform (win/mac/linux) but creates complexity in the binaries - loading the methods and creating the wrappers. The costs get higher if you have many methods that need to be loaded. Stub loader This approach involves using a stub loader component. The stub component is an
XPCOM component itself and when registered by
XPCOM, the code would sniff the runtime version and operating system Then the stub load the appropriate "real"
XPCOM component for the current configuration. It's pretty simple to do and the concept can be used to load third-party shared libraries (DLL, so, dylib) used in
XPCOM components. In this case, we would use the stub to load the right binary compone...
Resources
This material may be distributed only su...
...This material may be distributed only subject to the terms and ...
...This material may be distributed only subject to the terms and conditions set forth in the Open Public...
Components.Exception
See also nsIXPCException. ...
...CException. ...
...veloper-facing locations, defaulting to 'exception' result the nsresult value of the exception, which defaults to Components.results.NS_ERROR_FAILURE stack an
XPCOM stack to be set on the exception (defaulting to the current stack chain) data any additional data you might want to store, defaulting to null Example throw Components.Exception("I am throwing an Exception from a Javascript
XPCOM component."); ...
Components.classes
The properties of this object are indexed by the ContractID (or human-readable name) of the component class. ...
... The properties of this object are indexed by the ContractID (or human-readable name) of the component class. ...
...he Components.classes array as follows: var clazz0 = Components.classes["@mozilla.org/messenger;1"]; clazz0 is the class object for the ContractID @mozilla.org/messenger;1, which is not usually used by itself, but whose createInstance and getService methods can be used to create a new instance of the component or to access the singleton instance, if the contract ID represents a service. ...
Components object
l object using XPConnect. Some properties of Components require advanced privileges and may not work in web pages. ...
... utils.createObjectIn Creates a new obj...
...t with which a given object is associated (through its prototype chain at birth, for example). utils.getWeakReference Gets a weak reference for the object passed in. utils.import Loads a JavaScript module into the current script, without sharing a scope. utils.lookupMethod Looks up a native (i.e. declared in the interface) method or property of an
XPCOM object. Serves the same purpose as XPCNativeWrapper. utils.makeObjectPropsNormal Ensures that all functions come from the specified object's scope, and aren't cross-compartment wrappers. May only be called from JavaScript code. utils.methodjit Obsolete since Gecko 24.0 Provides access to the value of the methodjit property in the JavaScript environment. ...
NS_GetComponentManager
The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. ...
...The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. ...
...The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. ...
NS_GetComponentRegistrar
The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. ...
...The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. ...
...The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. ...
NS_GetServiceManager
The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. ...
...The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. ...
...The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. ...
nsMemory
HeapMinimize The HeapMinimize function attempts to shrink the size of the heap. Clone The Clone function creates a copy of an existing memory block up to the size specified. ...
...IMemory implementation without having to go through the service manager to get it. #include "nsMemory.h" class nsMemory { ... }; Methods Alloc The Alloc function allocates a block of memory of a particular size. Realloc The Realloc function reallocates a block of memory to a new size. Free The Free function frees a block of memory that was allocated by
XPCOM's memory manager. HeapMinimize The HeapMinimize function attempts to shrink the size of the heap. Clone The Clone function creates a copy of an existing memory block up to the size specified. GetGlobalMemoryService The GetGlobalMemoryService function returns a reference to
XPCOM's global nsIMemory object. Remarks To use the methods in this class, you mus...
... HeapMinimize function attempts to shrink the size of the heap. Clone The Clone function creates a copy of an existing memory block up to the size specified. GetGlobalMemoryService The GetGlobalMemoryService function returns a reference to
XPCOM's global nsIMemory object. Remarks To use the methods in this class, you must link your component or application against the
XPCOM glue library. The static methods defined on this class are not frozen. However, if you use these functions in your
XPCOM component, and if you link to the
XPCOM glue library, then your component will only have a runtime dependency on the frozen
XPCOM API. See also nsIMemory ...
nsIComponentRegistrar
xpcom/components/nsIComponentRegistrar.idlScriptable This interface provides methods to access and modify the
XPCOM component registry. Inherits from: nsISupports Last changed in Gecko 1.0 Method overview void autoRegister(in nsIFile aSpec); void autoUnregister(in nsIFile aSpec); string CIDToContractID(in nsCIDRef aClass); nsCIDPtr contractIDToCID(in string aContractID); nsISimpleEnumerator enumerateCIDs(); nsISimpleEnumerator enumerateContractIDs(); boolean isCIDRegistered(in nsCIDRef aClass); boolean isContractIDRegistered(in string aContractID); void registerFactory(in nsCIDRef aClass, in string aClassName, in string aContractID, in nsIFactory aFactory); void registerFactoryLocation(in nsCIDRef aClass, in string aClassName, in string aContractID, in nsIFi...
...ich this loader defines. For example, if the given file is a native library, it must export the symbol NSGetModule. Other loaders may have different semantics. This method may only be called from the main thread. void autoRegister( in nsIFile aSpec ); Parameters aSpec This parameter indicates either a component file to be registered or a directory containing component files to be registered.
XPCOM <= 1.8: If aSpec is null, then the application component's directory as defined by NS_
XPCOM_COMPONENT_DIR will be registered. See nsDirectoryService.
XPCOM >= 1.9: If aSpec is null, static components, GRE components, and the the application's component directories will be registered. See NS_GRE_DIR, NS_
XPCOM_COMPONENT_DIR, and NS_
XPCOM_COMPONENT_DIR_LIST in nsDirectoryService. autoUnregister() U...
...egister() Unregister a component file or all component files in a directory. This method may only be called from the main thread. void autoUnregister( in nsIFile aSpec ); Parameters aSpec This parameter indicates either a component file to be unregistered or a directory containing component files to be unregistered. If aSpec is null, then the application component's directory as defined by NS_
XPCOM_COMPONENT_DIR will be unregistered. See nsDirectoryService. CIDToContractID() This method returns the ContractID corresponding to a given ClassID. string CIDToContractID( in nsCIDRef aClass ); Parameters aClass The ClassID to be queried. Return value The ContractID corresponding to aClassID if one exists and is registered. contractIDToCID() Returns the ClassID for a given ContractID, if one...
nsIDirectoryService
The
XPCOM Directory Service implements this interface to provide support for a variety of well-known file and directory locations. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void init(); void registerProvider(in nsIDirectoryServiceProvider prov); void unregisterProvider(in nsIDirectoryServiceProvider prov); init() Initializes the nsIDirectoryService instance. This method must be called before an nsIDirectoryService instance can be used. In the case of the
XPCOM Directory Service, this method is called as part of
XPCOM initialization. ...
...file and directory locations. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void init(); void registerProvider(in nsIDirectoryServiceProvider prov); void unregisterProvider(in nsIDirectoryServiceProvider prov); init() Initializes the nsIDirectoryService instance. This method must be called before an nsIDirectoryService instance can be used. In the case of the
XPCOM Directory Service, this method is called as part of
XPCOM initialization. Must not be called by external code; called internally by
XPCOM initialization. void init(); Parameters None. registerProvider() Register a provider with the service. The directory service will keep a strong reference to the nsIDirectoryServiceProvider instances registered via registerProvider. The providers will be rele...
...Call unregisterProvider() to force the directory service to relinquish ownership of a particular provider instance. void registerProvider( in nsIDirectoryServiceProvider prov ); Parameters prov The nsIDirectoryServiceProvider to register with the service. unregisterProvider() Unregister a provider that was previously registered with the directory service. ...
nsIModule
It is the main entry point by which the system accesses an
XPCOM component. ...
...
xpcom/components/nsIModule.idlScriptable This interface must be implemented by each
XPCOM component. It is the main entry point by which the system accesses an
XPCOM component. Inherits from: nsISupports Last changed in Gecko 0.9.9 Method overview boolean canUnload(in nsIComponentManager aCompMgr); void getClassObject(in nsIComponentManager aCompMgr, in nsCIDRef aClass, in nsIIDRef aIID, [retval, iid_is(aIID)] out nsQIResult aResult); void registerSelf(in nsIComponentManager aCompMgr, in nsIFile aLocation, in string aLoaderStr, in string aType); void unregisterSelf(in nsIComponentManager aCompMgr, in nsIFile aLocation, in string aLoaderStr); Methods canUnload() This method may be queried to determine whether or not the component module c...
..., [retval, iid_is(aIID)] out nsQIResult aResult); void registerSelf(in nsIComponentManager aCompMgr, in nsIFile aLocation, in string aLoaderStr, in string aType); void unregisterSelf(in nsIComponentManager aCompMgr, in nsIFile aLocation, in string aLoaderStr); Methods canUnload() This method may be queried to determine whether or not the component module can be unloaded by
XPCOM. boolean canUnload( in nsIComponentManager aCompMgr ); Parameters aCompMgr The global component manager. Return value Indicates to the caller whether or not the component module can be unloaded. Returning true is not a guarantee that the module will be unloaded. It constitues only willingness of the module to be unloaded. It is very important to ensure that no outstanding references ...
nsITaskbarTabPreview
; this is done by Windows and cannot be prevented. When there are no more tab previews left for a window, the window preview is automatically made visible again. An application may have as many tab previews as memory allows. You can't directly instantiate this interface; instead, call the nsIWinTaskbar.createTaskbarTabPreview(). Method overview void EnsureRegistration(); Violates the
XPCOM interface guidelines nativeWindow GetHWND(); Violates the
XPCOM interface guidelines void move(in nsITaskbarTabPreview aNext); Attributes Attribute Type Description icon imgIContainer The icon displayed next to the title in the preview. This is null by default. title DOMString The title displayed above the thumbnail. By defaul...
...tes the
XPCOM interface guidelines void move(in nsITaskbarTabPreview aNext); Attributes Attribute Type Description icon imgIContainer The icon displayed next to the title in the preview. This is null by default. title DOMString The title displayed above the thumbnail. By default, this is an empty string. Methods Violates the
XPCOM interface guidelines EnsureRegistration() Used internally to ensure that the taskbar knows about this preview. If a preview is not registered, the API call to set its sibling (via the move() method) will fail silently. This method is only invoked when it's safe to make taskbar API calls. void EnsureRegistration(); Parameters None. ...
... nativeWindow GetHWND(); Parameters None. Return value The HWND for the preview's proxy window. move() Relocates the preview relative to another tab preview from the same window. ...
nsIVersionComparator
1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Version strings are dot-separated sequences of version-parts. A version-part consists of up to four parts, all of which are optional: <number-a><string-b><number-c><string-d (everything else)> A version-part may also consist of a single asterisk "*" which indicates * "infinity". Numbers are base-10, and are zero if left out. Strings are compared bytewise. For additional backwards compatibility, if "string-b" is "+" then "number-a" is incremented by 1 and "string-b" becomes "pre". ...
... are base-10, and are zero if left out. Strings are compared bytewise. For additional backwards compatibility, if "string-b" is "+" then "number-a" is incremented by 1 and "string-b" becomes "pre". ...
...pre". 1.0pre1 < 1.0pre2 < 1.0 == 1.0.0 == 1.0.0.0 < 1.1pre == 1.1pre0 == 1.0+ < 1.1pre1a < 1.1pre1 < 1.1pre10a < 1.1pre10 Implemented by: @mozilla.org/
xpcom/version-comparator;1. The service can be accessed directly via Services.vc after loading Services.jsm or with the following code: var versionComparator = Components.classes["@mozilla.org/
xpcom/version-comparator;1"] .getService(Components.interfaces.nsIVersionComparator); Method overview long compare(in ACString A, in ACString B); Methods compare() Compare two version strings. long compare( in ACString A, in ACString B ); Parameters A The first version. B The second version. Return value If A and B are two version...
Setting HTTP request headers
t like events or signals found in other languages and frameworks. In particular, to get the nsIHttpChannel just before the HTTP request is made we need to observe the "http-on-modify-request" topic. (And yes, "http-on-modify-request" is a string.) NOTE: There are many topics, besides just "http-on-modify-request", that you can get notifications about, for example "http-on-examine-response" and "
xpcom-shutdown". You can also make up your own topics and send out your own notifications. For more information about notifications framework and a list of common notification topics, see Observer Notifications. Observers To get notified about some topic (like "http-on-modify-request") we need to create an observer. An observer is a component implementing nsIObserver interface. And once the observer ...
...-request", false); }, unregister: function() { this.observerService.removeObserver(this, "http-on-modify-request"); } }; This object has a convenience register() and unregister() methods, so in order to activate it you just need to call: httpRequestObserver.register(); You should also remember to unregister the observer at shutdown: httpRequestObserver.unregister(); And that's it. ...
...er() methods, so in order to activate it you just need to call: httpRequestObserver.register(); You should also remember to unregister the observer at shutdown: httpRequestObserver.unregister(); And that's it.
XPCOM components You need to register a single http-on-modify-request observer per application (and not one per window). This means that you should put the observer's implementation in an
XPCOM component instead of an overlay. If you want to support Gecko2 (Firefox4) you need to register your javascript component as described here: https://developer.mozilla.org/en/
XPCOM/
XPCOM_changes_in_Gecko_2.0#JavaScript_components. var headerName = "X-hello"; var headerValue = "world"; function LOG(text) { // var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getServic...
Frequently Asked Questions
p you find what you're looking for faster. In most cases, the answer will just refer back into the reference manual, above. No need to explain things twice :-). Buildtime Errors The build just broke. It's not in your code, or it's not on your platform, but there's an nsCOMPtr on the line where the error is and you're suspicious. You're looking in the right place. ...
...nto the reference manual, above. No need to explain things twice :-). Buildtime Errors The build just broke. It's not in your code, or it's not on your platform, but there's an nsCOMPtr on the line where the error is and you're suspicious. You're looking in the right place. comparing an nsCOMPtr to a raw
XPCOM interface pointer declaring an nsCOMPtr to a forward-declared class not linking to
XPCOM not including nsCOMPtr.h different settings of NSCAP_FEATURE_DEBUG_PTR_TYPES Runtime Errors NS_ASSERTION "QueryInterface needed" May be caused by a class that derives from a given interface, when you forgetting to also specify the interface name in the NS_IMPL_ISUPPORTS / NS_IMPL_THREADSAFE_ISUPPORTS macro. For example, the assertion occurs when you convert the pointer to the object to a ra...
...r, &rv) ); if ( foo ) foo->DoSomeFooThing(); // |foo| goes out of scope, and so |Release|s its referent, here } // ...tons of stuff here, during which I don't need an |nsIFoo| return rv; } Editors Note: Move this discussion to the efficiency section, and link to it from here. make an nsCOMPtr leak (for a debug test)? call a getter that uses a raw
XPCOM interface pointer as an `in/out' parameter? call a getter that fills in an nsIFoo*& parameter? call a getter that doesn't AddRef its result? Any
XPCOM function that returns an interface pointer, i.e., a `getter', must have already AddRefed that pointer. If it didn't, you should probably report it as a bug. No matter which code pattern you use to solve this problem, you should comment it, e.g.,...
Weak reference
If the referent object is destroyed before the weak reference, the pointer inside the weak reference is set to nsnull. Why do I need this? When you hold an owning reference on an object (i.e., you have AddRefed it), you are holding that object in existence for the duration of your reference. This isn't always appropriate, and can lead to trouble. If, for instance, this owning reference is part of a cycle of owning references (e.g., if the referenced object also holds a owning reference back to you), then none of the objects in the cycle can be reclaimed without taking special measures. There are less severe situations. ...
...t in situations where you need this, there are two alternatives which you may want to consider: You might hold an owning reference, but arrange to Release it out-of-band; this must be before the destructor, which would otherwise never be called. You might hold a raw pointer (without AddRefing and Releaseing it), and avoid using it in cases where it might dangle. ...
..., there are two alternatives which you may want to consider: You might hold an owning reference, but arrange to Release it out-of-band; this must be before the destructor, which would otherwise never be called. You might hold a raw pointer (without AddRefing and Releaseing it), and avoid using it in cases where it might dangle. See also The source
xpcom/base/nsIWeakReference.idl
xpcom/glue/nsWeakReference.h
xpcom/glue/nsWeakReference.cpp
XPCOM ownership guidelines Using nsCOMPtr Original Document Information Author: Scott Collins Last Updated Date: September 23, 2000 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Working with Multiple Versions of Interfaces
In the extension that prompted this note, I needed to obtain the HWND of the document (yes its on Windows) in order to identify each particular extension instance. To do this I used the accessibility framework: HWND getHwnd(nsIDOMNode *node){ HWND self = NULL; nsresult rv; nsCOMPtr<nsIAccessibleRetrieval> refp; refp = do_CreateInstance( "@mozilla.org/accessibleRetrieval;1", &rv); if (NS_FAILED(rv)){ return self; } //line 6. ...
...cessibleRetrieval). Unfortunately we compiled this in the latest SDK, and so this magic number happens to be: "244e4c67-a1d3-44f2-9cab-cdaa31b68046" whereas, inside Firefox 2, the IID it happens to know about is: "663ca4a8-d219-4000-925d-d8f66406b626". and this explains our NS_ERROR_NO_INTERFACE. Fortunately there is a plan of action that we can follow to rectify this. We build construct our
XPCOM component so that first tries to get the interface by it's new IID, then if that fails, attempts plan B. Plan B is simply trying to get the interface by it's older IID. For expository purposes we will do this in two stages; buoyed by the fact that it is the actual route we took. The Optimist's Solution The first thing we do is replace line 6 above by our plan B: if (NS_FAILED(rv)){ return g...
...id *wh = NULL; nsCOMPtr<nsIAccessibleDocument> accdocnode; rv = accnode->QueryInterface(IAD_IID_OLD, getter_AddRefs(accdocnode)); if(NS_FAILED(rv)){ return self; } rv = accdocnode->GetWindowHandle(&wh); if(NS_SUCCEEDED(rv)){ self = static_cast<HWND>(wh); } return self; } There is good news and bad news. First the good news. Plan B inside Firefox 2 happily runs to completion. All the
XPCOM calls succeed, or at least think they succeed. The bad news is that the thing we get back is not a valid HWND. The problem now is not just interface identifier mismatch, but class declaration mismatch. GetWindowHandle is the tenth method declared in the nsIAccessibleDocument.h that Firefox 2 was built with, but actually the eighth method in the SDK that I used to build my extension (and hence X...
SDK and XUL Comparison - Archive of obsolete content
or developing add-ons on the new native version of Firefox Mobile. See the tutorial on mobile development. Advantages of XUL-based Add-ons User interface flexibility XUL overlays offer a great deal of options for building a UI and integrating it into the browser. Using only the SDK's supported APIs you have much more limited options for your UI. ...
...e development. Advantages of XUL-based Add-ons User interface flexibility XUL overlays offer a great deal of options for building a UI and integrating it into the browser. Using only the SDK's supported APIs you have much more limited options for your UI.
XPCOM Traditional add-ons have access to a vast amount of Firefox functionality via
XPCOM. The SDK's supported APIs expose a relatively small set of this functionality. Low-level APIs and Third-party Modules That's not the whole story. If you need more flexibility than the SDK's High-Level APIs provide, you can use its Low-level APIs to load
XPCOM objects directly or to manipulate the DOM directly as in a traditional bootstrapped extension. Alternatively, you can load thi...
Creating Reusable Modules - Archive of obsolete content
th, and produces a short, fixed length string of bytes as output. It's a useful way to create a "fingerprint" that can be used to identify a file. MD5 is a commonly used hash function: although it's no longer considered secure, it works fine outside a security context. Here we'll write an add-on that lets the user select a file on disk and calculates its hash. For both these operations we'll use
XPCOM interfaces. File picker To let the user select a file we'll use nsIFilePicker. The documentation for that interface includes an example which we can adapt like this: var {Cc, Ci} = require("chrome"); function promptForFile() { const nsIFilePicker = Ci.nsIFilePicker; var fp = Cc["@mozilla.org/filepicker;1"] .createInstance(nsIFilePicker); var window = require("sdk/window/uti...
... fp.show(); if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) { var file = fp.file; // Get the path as string. Note that you usually won't // need to work with the string paths. var path = fp.file.path; // work with returned nsILocalFile... } return path; } Hash function Firefox has built-in support for hash functions, exposed via the nsICryptoHash
XPCOM interface The documentation page for that interface includes an example of calculating an MD5 hash of a file's contents, given its path. We can adapt it like this: var {Cc, Ci} = require("chrome"); // return the two-digit hexadecimal code for a byte function toHexString(charCode) { return ("0" + charCode.toString(16)).slice(-2); } function md5File(path) { var f = Cc["@mozilla.org/file/loca...
File I/O - Archive of obsolete content
Note: File objects are nsIFile. For legacy reasons, there is also an nsILocalFile interface. ...
...e\Start Menu\Programs). This is a Windows-specific value. TmpD d The operating system's temporary files directory (for example, /tmp on Mac OS X and Linux). UChrm f The user chrome directory in their profile: %profile%/chrome. resource:app d The application directory in an XULRunner application. Look in the source for other strings available:
xpcom/io/nsAppDirectoryServiceDefs.h,
xpcom/io/nsDirectoryServiceDefs.h. Other such keys as the "ProfD" key are available; check the known locations. Enumerating drives on Windows While you can use initWithPath("/") on UNIX-like systems (Linux, Mac) to get the root of the file system, there's no such root on Windows. However, you can enumerate available drives using the following code: Components.
Progress Listeners - Archive of obsolete content
h means you don't get any notifications for inactive tabs. Firefox 3.5 includes a way to set up a listener for all tabs, selected and not: Listening to events on all tabs. ...
...l, init: function() { gBrowser.addProgressListener(this); }, uninit: function() { gBrowser.removeProgressListener(this); }, processNewURL: function(aURI) { if (aURI.spec == this.oldURL) return; // now we know the url is new... ...
Code snippets - Archive of obsolete content
ed code Forms Forms related code XML Code used to parse, write, manipulate, etc. XML File I/O Code used to read, write and process files Drag & Drop Code used to setup and handle drag and drop events Dialogs Code used to display and process dialog boxes Alerts and Notifications Modal and non-modal ways to notify users Preferences Code used to read, write, and modify preferences JS
XPCOM Code used to define and call
XPCOM components in JavaScript Running applications Code used to run other applications <canvas> related WHAT WG Canvas-related code Signing a XPI How to sign an XPI with PKI Delayed Execution Performing background operations. Miscellaneous Miscellaneous useful code fragments HTML to DOM Using a hidden browser element to parse HTML to a window's DOM Jav...
... External links The content at MozillaZine Example Code is slowly being moved here, but you can still find useful examples there for now. ...
Enhanced Extension Installation - Archive of obsolete content
ompatibility information held by the item. If there is, and this remote information makes it so that the item is now compatible with the running version of the application, the item is configured in the manner described above (metadata written, added to container). Finalization For Themes, the item is immediately installed fully, rather than awaiting the next restart, since Themes do not supply
XPCOM components, preferences defaults etc. For Extensions, on the next startup, the startup system notices the presence of the .autoreg file and starts the Extension manager with a "dirty" flag, telling it to finish any install operations that may be pending. The Extension manager loads the XML/RDF datasources (this is allowable and necessary because a major change has happened) and gets a list of a...
...ponent Manager, Preferences System and Chrome Registry can locate additional files on the next start. The finalization process then notifies the startup process that finalization has changed this manifest, and that the application must be restarted to pick up changes specified therein. The startup process receives this "needsRestart" bit when the Extension manager's startup completes, shuts down
XPCOM and relaunches the application. On the next restart, the XREDirProvider now supplies a list of directories to requesting systems listing the new item's components, defaults and chrome manifests. Uninstallation, Disabling, Enabling These functions work on the same principle as installation - the user requests an action through the UI while the application is running and metadata is written (toBe...
Extension Etiquette - Archive of obsolete content
jects. Global variables, such as top-level declarations on scripts loaded into shared windows or web pages. Expando properties of shared objects, such as document objects, or DOM nodes. IDs and class names in HTML and XUL documents, when extensions add elements to web pages or browser windows. chrome: or resource: packages, which are often defined in chrome.manifest files. about: page URLs.
XPCOM contract IDs, which are often registered in chrome.manifest files. While these are among the most common examples of namespaces in which conflicts can occur, there are many others. In general, care must be taken whenever defining a name anywhere that other code might do likewise. Strategies to avoid such conflicts include: Avoid shared namespaces where possible Many naming conflicts are bes...
..., the simplest solution to prevent conflicts is to use a distinct prefix for all of your names. Class names for HTML elements created by the Cool Beans extension, for instance, might all be prefixed with cool-beans-. Global variables might all be defined as properties of the CoolBeans object. Some namespaces have specific conflict prevention conventions, which should be followed as appropriate.
XPCOM contract IDs, for instance, should always begin with an @, followed by a domain name that the author controls, e.g., "@example.com/foo/bar;1" It is important that the prefix that you use be unlikely to conflict with other code, and that it be indicative of the name of your add-on. Generic prefixes such as myextension-, or short prefixes such as ffx-, are likely to be used elsewhere, and therefo...
Firefox addons developer guide - Archive of obsolete content
The Firefox add-ons developer guide was contributed by the Mozilla Japan community; it covers how to go about building Firefox extensions using
XPCOM and XUL. These days, we recommend using the Add-on SDK instead, but there are times when you need the additional control offered by a more direct approach. ...
...e Mozilla Japan community; it covers how to go about building Firefox extensions using
XPCOM and XUL. These days, we recommend using the Add-on SDK instead, but there are times when you need the additional control offered by a more direct approach. ...
Tabbed browser - Archive of obsolete content
ill work equally well for other XUL elements. This will only work in an overlay of browser.xul. XUL: <menuitem oncommand="myExtension.foo(event)" onclick="checkForMiddleClick(this, event)" label="Click me"/> JS: var myExtension = { foo: function(event) { openUILink("http://www.example.com", event, false, true); } } Opening a URL in an on demand tab Cu.import("resource://gre/modules/
XPCOMUtils.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "gSessionStore", "@mozilla.org/browser/sessionstore;1", "nsISessionStore"); // Create new tab, but don't load the content. var url = "https://developer.mozilla.org"; var tab = gBrowser.addTab(null, {relatedToCurrent: true}); gSessionStore.setTabState(tab, JSON.stringify({ ...
...er.xml for corresponding XBL bindings (or just look at the current reference pages on browser and tabbrowser. Getting the browser that fires the http-on-modify-request notification See the Observer notifications page for information on http-on-* notifications. 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. Warning: This code should be updated to use nsILoadContext instead of getInterface(Components.interfaces.nsIDOMWindow). UPDATED EXAMPLE IS IN SECTION BELOW THIS observe: function (subject, topic, data) { if (topic == "http-on-modify-request") { subject.QueryInterface(Components.interfaces.nsIHttpChannel); var url = subj...
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
roductx.y\. The keys "Product x.y" contain application keys for the given Mozilla based browser. Example: Netscape 6 6.1\ Look at the Extensions subkey, e.g. HKEY_LOCAL_MACHINE\Software\Mozilla\Netscape 6 6.1\Extensions\ Access the Plugins value and value-data pair, e.g: Plugins = C:\Program Files\Netscape\Netscape 6\Plugins. You also have the Components value and value-data pair; this is for
XPCOM components. In addition, if you have made your plugin scriptable and accessible from JavaScript, you ought to put the associated XPT file in the Components directory. You can access the Components value and value-data pair (telling you where the Components directory is) in a similar manner, e.g.: Components=C:\Program Files\Netscape\Netscape 6\Components. Future Mozilla based browsers won't disti...
...nents directory. You can access the Components value and value-data pair (telling you where the Components directory is) in a similar manner, e.g.: Components=C:\Program Files\Netscape\Netscape 6\Components. Future Mozilla based browsers won't distinguish between plugins and components, and will pick both up from a common location. However, for Netscape 6.1 and Netscape 6.2, XPT files, as well as
XPCOM Plugins, ought to go in the Components directory. On these browsers, this is the only directory that can "pick up" an XPT file, as well the only directory that can recognize
XPCOM components. You now have information about the Plugins directory for Gecko embedding browsers. Examples given for "Product x.y" were using Netscape 6 but other possible Mozilla based browsers exist as well; all Gecko-...
Java in Firefox Extensions - Archive of obsolete content
text of Firefox extensions."). These 2 objects let you make use of the standard JDK classes, e.g., var aJavaList = new java.util.LinkedList(); If you want to load your own JARs, then you can create your own Java class loader. The following technique only works in JavaScript code linked from or contained in XUL files. If you wish to call Java code from within JavaScript code that implements some
XPCOM components, at this time, you need a different technique (refer to the complete Java Firefox Extension). A good reason for calling Java from within an
XPCOM component rather than from XUL is to maintain a singleton (some singular Java object) across all Firefox windows. If you call Java from XUL, then each Firefox window will have its own class loader and hence its own "singleton". The following ...
...[NOTE: A simpler Hello World version than that below is now available at http://brett-zamir.me/java_demo/ ] For privileges, the basic procedure is: Download and include http://simile.mit.edu/repository/jav...nsionUtils.jar within your extension (you can also build your own from the source files at http://simile.mit.edu/repository/jav...xtensionUtils/ ) Build and add references leadi...
Unix stub installer - Archive of obsolete content
e gdb to debug the installer run it by typing "gdb mozilla-installer-bin" on the shell prompt. How we get setup to debug the XPInstall engine from the unix stub installer? Build your entire mozilla tree (which should build the installer in the src2 directory as well). Go to mozilla/xpinstall/packager/unix. On the shell prompt type "perl deliver.pl". Now you will find an installer *and* the
xpcom.xpi and other debug xpis delivered to mozilla/installer/raw. Debug using "gdb mozilla-installer-bin" and set a breakpoint at XPI_Init(). You can step into the XPInstall engine through the xpistub once the xpistub dll is loaded. How do I add an installer package to the unix installer? Adding a package involves a few steps: Add a section named for your <component> to the packages-unix manif...
...a-installer-bin" and set a breakpoint at XPI_Init(). You can step into the XPInstall engine through the xpistub once the xpistub dll is loaded. How do I add an installer package to the unix installer? Adding a package involves a few steps: Add a section named for your <component> to the packages-unix manifest that describes which files from dist belong to which module. For example, see the
xpcom section that lists all the shared libraries as seen in dist. These are eventually zipped with the directory structure preserved. Read the top of the packages-unix file for it's simple syntax and semantics. Add an <component>.jst install script template file (the jst extension stands for javascript template indicating this is a template for the final install.js for the <component>.xpi. Checkin th...
Windows stub installer - Archive of obsolete content
etup to debug the Windows stub installer? Build your entire mozilla tree, which should build the stub installer in the setup directory as well. (If you need to rebuild stub installer, got to /mozilla/xpinstall/wizard/windows/setup and type "nmake /f makefile.win") Go to mozilla/xpinstall/wizard/windows/builder On the shell prompt type "perl build.pl". Now you will find an installer *and* the
xpcom.xpi and other debug xpis delivered to mozilla/dist/WIN32_D.OBJ/install. Run the stub installer setup.exe from the install directory. If you need to use VC++ to debug the installer: Under Project | Settings | Debug Set "Executable for Debug Session" to be the path to mozilla/dist/WIN32_D.OBJ/install/setup.exe Set "Working Directory" to be the path to mozilla/dist/WIND32_D.OBJ/install Press ...
...s F10 to step into the code How we get setup to debug the XPInstall engine from the Windows stub installer? This section needs to be added How do I add an installer package to the Windows installer? Adding a package involves a few steps: Add a section named for your <component> to the packages-win manifest that describes which files from dist belong to which module. For example, see the
xpcom section that lists all the shared libraries as seen in dist. These are eventually zipped with the directory structure preserved. Read the top of the packages-win file for it's simple syntax and semantics. Add an <component>.jst install script template file. The jst extension stands for javascript template indicating this is a template for the final install.js for the <component>.xpi. Checkin the...
Accessing Files - Archive of obsolete content
ptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative
XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. Accessing Files This section describes how to create a file reference. Retrieving a File W...
...nstance, this will be the directory where the application was launched from, which may be different from the 'Application' value. Profile The profile directory where preferences are stored. Desktop The desktop directory. Usually, you would use this as the default directory for saving files. Components The components directory where
XPCOM components are installed. Temp The temporary directory. You would store any temporary or cache files here. There are a number of other values that may be used, most of which are platform specific. For instance, on Windows, the value 'Strt' returns the Start directory, where applications which run when the system starts up are placed. On other platforms, using this v...
Styling a Tree - Archive of obsolete content
e every fourth row have blue text, using the example from a previous section. We'll need to add code to the getCellProperties() function, to add a property 'makeItBlue' for cells in every fourth row. (We don't use getRowProperties() as the text color will not be inherited into each cell.) Prior to Gecko 22 the properties object that is passed as the last argument to the getCellProperties() is an
XPCOM object that implements nsISupportsArray. It is really just an
XPCOM version of an array. It contains a function AppendElement() which can be used to add an element to the array. We can use the interface nsIAtomService to construct string atoms for the properties. getCellProperties: function(row,col,props){ if ((row %4) == 0){ var aserv=Components.classes["@mozilla.org/atom-service;1"]. ...
... the properties. getCellProperties: function(row,col,props){ if ((row %4) == 0){ var aserv=Components.classes["@mozilla.org/atom-service;1"]. getService(Components.interfaces.nsIAtomService); props.AppendElement(aserv.getAtom("makeItBlue")); } } The properties list requires an array of atom objects, which can be thought of as constant strings. We create them using the
XPCOM interface nsIAtomService and add them to the array using the AppendElement() function. Here, we create an atom 'makeItBlue'. You can call AppendElement() again to add additional properties. From Gecko 22 your function should return a string containing the property. getCellProperties: function(row,col){ if ((row %4) == 0){ return "makeItBlue"; } } To support Gecko versions before and af...
stringbundle - Archive of obsolete content
strings Type: nsISimpleEnumerator An enumeration of all of the strings in the string bundle. The enumeratio...
... strings Type: nsISimpleEnumerator An enumeration of all of the strings in the string bundle. The enumeration contains nsIPropertyElement objects. ...
Building XULRunner - Archive of obsolete content
XULRunner is built using basically the same process as Firefox or other applications. Please read and follow the general Build Documentation for instructions on how to get sources and set up build prerequisites. By default, XULRunner is built with Java
XPCOM support; the build system must be able to find an appropriate JDK on the system; see the instructions on Building Java
XPCOM for more details. If you do not want to build Java
XPCOM support, specify --disable-java
xpcom in your configuration. On Mac, XULRunner requires Mac OS X 10.3 or higher and XCode 1.5 or higher to build properly. The runtime requirement is Mac OS X 10.2. A basic minimal mozconfig which will build a release configuration of XULRunner is: mk_add_options MOZ_CO_PROJECT=xulrunner mk_add_options MOZ_OBJDIR=@topsrcdir@/obj-...
...ires Mac OS X 10.3 or higher and XCode 1.5 or higher to build properly. The runtime requirement is Mac OS X 10.2. A basic minimal mozconfig which will build a release configuration of XULRunner is: mk_add_options MOZ_CO_PROJECT=xulrunner mk_add_options MOZ_OBJDIR=@topsrcdir@/obj-xulrunner ac_add_options --enable-application=xulrunner #Uncomment the following line if you don't want to build Java
XPCOM: #ac_add_options --disable-java
xpcom CVS tags and XULRunner versions Older XULRunner releases where tagged in CVS with (for instance XULRUNNER_1_8_0_5_RELEASE ) up to version 1.8.0.5 The CVS repository does not have specific tags for XULRunner anymore. Instead a XULRunner build is a just special build made from the Firefox/Mozilla tree, using the same tag as a Firefox build. There is a conven...
Dialogs in XULRunner - Archive of obsolete content
Macintosh has always had them. It makes creating an application easier for developers; in addition, the consistent user experience also makes applications easier to use. XUL supports native implementations of filepickers (Mozilla terminology for File Open and Save dialogs). Newer releases will allow using preferences to switch to a XUL emulation filepicker, if you want to. ...
...// --- do something with the file here --- } } XUL does not currently support any other common dialogs. That could change in future releases. Firefox and Thunderbird both support nearly native Page Setup and Print dialogs. However, XUL does support elements to make creating wizards a simple task as well. Future articles in this series will look at input controls, printing, the clipboard, and
XPCOM. See also dialog XUL Tutorial:Creating Dialogs nsIFilePicker XUL Tutorial:Open and Save Dialogs << Previous Original Document Information Author: Mark Finkle Last Updated Date: October 2, 2006 ...
Getting started with XULRunner - Archive of obsolete content
tion. There is an article with a more complicated approach to building XULRunner applications at Creating XULRunner Apps with the Mozilla Build System. If you need to change XULRunner itself or integrate it with external binaries you may need to read that article. Step 1: Download XULRunner You can find a download link on the main XULRunner page here on MDN. Since we are not creating any binary
XPCOM components, we only need to download and install the XULRunner runtime package, not the SDK. The XULRunner download for Windows is a zip file, not a true install. As a developer, I like the idea that XULRunner only needs to be unzipped onto my machine. I am assuming that it doesn't need to hook into my Windows system and that's a good thing. It also means that the XULRunner is portable so, if yo...
...there are 5 files in the folder structure: application.ini, chrome.manifest (2), prefs.js, and main.xul. The /chrome/chrome.manifest file is optional, but might be useful for backward compatibility. See the note below. For more details on the structure of installable bundles in general see: Structure of an installable bundle. Note: In XULRunner 2.0, the chrome.manifest is now used to register
XPCOM components in addition to its previous uses. Part of this change means the /chrome/chrome.manifest is no longer considered the "root" manifest. XULRunner will not check that folder location for a root-level chrome.manifest. You need to move your existing chrome.manifest to the application root folder, remembering to update the relative paths within the file. You could also just create a new appli...
Make your xulrunner app match the system locale - Archive of obsolete content
Also, this may not be the proper way to do this and it may not work for you in all cases. Please update if there are more correct ways to do this. The first step is to get the code we're about to write to run before any of the locale specific resources are loaded. Democracy does this by creating a command line handler called DemocracyCLH, and then creating a new object of our PyBridge component. The code described lives in the PyBridge component's onStartup method which gets called automatically. The second step is to figure out the system locale. To be finished later. ...
...mocracy does this by creating a command line handler called DemocracyCLH, and then creating a new object of our PyBridge component. The code described lives in the PyBridge component's onStartup method which gets called automatically. The second step is to figure out the system locale. To be finished later. Then set the locale preference. The following is python code to set this preference. ...
2006-11-10 - Archive of obsolete content
Announcements There are no announcements this week. Meetings There were no m...
... Announcements There are no announcements this week. Meetings There were no meetings this week. Summarized By: Vanessa Miranda & Mohammad Tirtashi ...
2006-11-3 - Archive of obsolete content
Discussions Problem linking libraries to
XPCOM component A discussion involving a problem with linking third party library to
XPCOM component. ...
... Summary: mozilla.dev.tech.
xpcom - Oct 28-Nov 3, 2006 Announcements None during this week. Discussions Problem linking libraries to
XPCOM component A discussion involving a problem with linking third party library to
XPCOM component. Meetings None during this week. ...
XForms Custom Controls - Archive of obsolete content
ke input, output, trigger, etc. We will also show you how to create custom controls that work with the XForms model and are automatically updated just like XForms controls. The purpose of this article is to give you enough background information so that you'll be able to get a good start. To really grasp the following information, a good understanding of XForms, XBL, JavaScript and CSS is needed.
XPCOM knowledge will certainly not hurt. But even if you are only comfortable with a couple of these technologies, we hope that the possibilities outlined below will inspire you to learn more where you need to. Implementation Status The framework we use in the Mozilla XForms processor is very much a "work in progress". Please keep in mind that just about everything we mention here may change to some de...
...code to get some great examples of how XForms controls can be written. This will also allow you to be up to date with our current approaches (often the result of hard-learned lessons) and that will hopefully help you to more easily write your own controls. To get started, you really only need to know the language where you'd like to use XForms (like XHTML or XUL), some XBL and JavaScript, and the
XPCOM interfaces we are exposing for your use. Details Interfaces This section describes interfaces you need to know. There are two main groups of interfaces -> callback interfaces that must be implemented by the custom controls and the interfaces that custom controls can use to access the Mozilla XForms engine. nsIXFormsUIWidget Every custom control should implement the nsIXFormsUIWidget interface. Th...
Gecko FAQ - Gecko Redirect 1
t the open standards listed above so that they can have a rich, powerful formatting system and object model at their disposal, and "write once, view anywhere." Gecko's robust support for these standards makes Gecko the platform of choice for web content and web application developers worldwide. ...
...tform of choice for web content and web application developers worldwide. Are Gecko's APIs based on ActiveX? COM? JavaBeans? Gecko is reusable on all platforms thanks to
XPCOM, a subset of COM that works across platforms. COM, developed by Digital and later adopted by Microsoft, is the de facto standard for modular interfaces on Windows platforms. Additionally, on the Windows platform, Gecko's
XPCOM interfaces are wrapped in an ActiveX control that VB developers can utilize (ActiveX wrappers are not available on other platforms because ActiveX is a Windows-only technology). A JavaBean wrapper is not currently under development, but there is nothing in Gecko's architecture that precludes such development in the future. Source code and documentation for these interfaces are available through ...
Chrome registration
matically. interfaces interfaces component/mycomponent.xpt [flags] Instructs Mozilla to load interface information from a typelib file produced by XPIDL. Prior to Firefox 4, files in the components directory were registered automatically. component component {00000000-0000-0000-0000-000000000000} components/mycomponent.js [flags] Informs Mozilla about a component CID implemented by an
XPCOM component implemented in JavaScript (or another scripting language, if applicable). The ClassID {0000...} must match the ClassID implemented by the component. To generate a unique ClassID, use a UUID generator program or site. contract contract @foobar/mycontract;1 {00000000-0000-0000-0000-000000000000} [flags] Maps a contract ID (a readable string) to the ClassID for a specific implementat...
...e. osversion An extension or theme may need to operate differently depending on which version of an operating system is running. For example, a theme may wish to adopt a different look on Mac OS X 10.5 than 10.4: osversion>=10.5 abi If a component is only compatible with a particular ABI, it can specify which ABI/OS by using this directive. The value is taken from the nsIXULRuntime OS and
XPCOMABI values (concatenated with an underscore). For example: binary-component component/myLib.dll abi=WINNT_x86-MSVC binary-component component/myLib.so abi=Linux_x86-gcc3 See
XPCOM ABI for more details. platform (Platform-specific packages) Some packages are marked with a special flag indicating that they are platform specific. Some parts of content, skin, and locales may be different based o...
Command line options
plication build for and running atop the X11/X.org display and window system to be found on Linux and other Unix-based systems. --class=WM_CLASS Set the WM_CLASS resource class of the X11 windows created by the application. --display=DISPLAY Set the X display to use. --g-fatal-warnings Make all warnings fatal. --sync Make X calls synchronous. ...
...r and running atop the X11/X.org display and window system to be found on Linux and other Unix-based systems. --class=WM_CLASS Set the WM_CLASS resource class of the X11 windows created by the application. --display=DISPLAY Set the X display to use. --g-fatal-warnings Make all warnings fatal. --sync Make X calls synchronous. ...
Creating Sandboxed HTTP Connections
Introduction Starting with Gecko 1.8.1 (Firefox 2), it is possible to create sandboxed HTTP connections which don't affect the user's cookies. This article will cover the basics of doing HTTP connections from
XPCOM JavaScript, and should easily translate to C++
XPCOM. Setting up an HTTP connection The first step in setting up an HTTP connection from an URL (stored in a string) is to create an nsIURI out of it. nsIURI is an
XPCOM representation of an URI, with useful methods to query and manipulate the URI. To create an nsIURI from an string, we use the newURI method of nsIIOService: // the IO service var ioService = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); // create an nsIURI var uri = ioServic...
...NS_NOINTERFACE; } }, // nsIProgressEventSink (not implementing will cause annoying exceptions) onProgress : function (aRequest, aContext, aProgress, aProgressMax) { }, onStatus : function (aRequest, aContext, aStatus, aStatusArg) { }, // nsIHttpEventSink (not implementing will cause annoying exceptions) onRedirect : function (aOldChannel, aNewChannel) { }, // we are faking an
XPCOM interface, so we need to implement QI QueryInterface : function(aIID) { if (aIID.equals(Components.interfaces.nsISupports) || aIID.equals(Components.interfaces.nsIInterfaceRequestor) || aIID.equals(Components.interfaces.nsIChannelEventSink) || aIID.equals(Components.interfaces.nsIProgressEventSink) || aIID.equals(Components.interfaces.nsIHttpEventSink) || ...
Adding APIs to the navigator object
Starting with Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6), you can easily add new APIs to the window.navigator object by using the Category Manager. Simply add an entry to the "JavaScript-navigator-property" category. The object must be implemented as an
XPCOM component. Each method below of adding new objects to the navigator object requires that the new object is a registered
XPCOM component. You can read about creating and registering
XPCOM components in JavaScript. Programmatically adding an object to navigator var categoryManager = Components.classes["@mozilla.org/categorymanager;1"] .getService(Components.interfaces.nsICategoryManager); categoryManager.addCategoryEntry("JavaScript-navigator-property", "myApi", MY_CONTRACT_ID, ...
...ents.interfaces.nsICategoryManager); categoryManager.addCategoryEntry("JavaScript-navigator-property", "myApi", MY_CONTRACT_ID, false, true); This adds a new object, myApi, to the window.navigator object. The newly added object is a reference to the component specified by the contract ID MY_CONTRACT_ID. You can learn more about Contract IDs are unique text identifiers for
XPCOM components. Using a manifest to add an object to navigator You can also add an object to the window.navigator object by using the chrome manifest of an add-on: component {ffffffff-ffff-ffff-ffff-ffffffffffff} MyComponent.js contract @mozilla.org/mycomponent;1 {ffffffff-ffff-ffff-ffff-ffffffffffff} category JavaScript-navigator-property myComponent @mozilla.org/mycomponent;1 Generate a GUID a...
Makefile - variables
EXPORTS A list of exported header files and sources to install for external use. EXPORTS_NAMESPACES Exported package include directory: dist/include/${namespace} EXPORTS_${namespace} A list of exports/headers that should be copied into the exported namespace directory. EXTRA_COMPONENTS nsDefaultCLH.manifest, JavaScript
XPCOMM files EXTRA_DSO_LIBS EXTRA_DSO_LDOPTS EXTRA_JS_MODULES EXTRA_PP_COMPONENTS
XPCOMM files to pre-process before installation. GARBAGE A "clean target" macro containing a list of files to remove. GARBAGE_DIRS A "clean target" macro containing a list of directorie...
...R MOZ_CHROME_MULTILOCALE A list of locale names to process MOZ_CHROME_FILE_FORMAT both, file, jar, omni, symlink PACKAGER_NO_LIBS Hack to allow one makefile to include another without pulling in libs:: target definitions. STAGEDIST Local staging directory for localization and packaging. Todo:
xpcom/xpinstall variables: https://developer.mozilla.org/en/Adding_
XPCOM_components_to_Mozilla_build_system ...
How Mozilla's build system works
Makefile - targets Makefile - variables, values Makefile - *.mk files & user config Building libraries There are three main types of libraries that are built in Mozilla: Components are shared libraries (except in static builds), which are installed to dist/bin/components. Components are not linked against by any other library. Non-component shared libraries include libraries such as lib
xpcom and libmozjs. These libraries are installed to dist/bin and are linked against. You will probably not need to create a new library of this type. Static libraries are often used as intermediate steps to building a shared library, if there are source files from several directories that are part of the shared library. Static libraries may also be linked into an executable. Non-component shared li...
...is type. Static libraries are often used as intermediate steps to building a shared library, if there are source files from several directories that are part of the shared library. Static libraries may also be linked into an executable. Non-component shared libraries A non-component shared library is useful when there is common code that several components need to share and sharing it through
XPCOM is not appropriate or not possible. As an example, below is a portion of the makefile for libmsgbaseutil, which is linked against by all of the main news components: DEPTH = ../../.. topsrcdir = @top_srcdir@ srcdir = @srcdir@ VPATH = @srcdir@ include $(DEPTH)/config/autoconf.mk MODULE = msgbaseutil LIBRARY_NAME = msgbaseutil EXPORT_LIBRARY...
Simple Instantbird build
matically by the hg clone command), and run: ./mozilla/mach build mach is our command-line tool to streamline common developer tasks. See the mach article for more. Building can take a significant amount of time, depending on your system, OS, and chosen build options. Linux builds on a fast box may take under 15 minutes, but Windows builds on a slow box may take several hours. ...
..../mozilla/mach build mach is our command-line tool to streamline common developer tasks. See the mach article for more. Building can take a significant amount of time, depending on your system, OS, and chosen build options. Linux builds on a fast box may take under 15 minutes, but Windows builds on a slow box may take several hours. Building purple
xpcom and libpurple First download the purple
xpcom code: hg clone http://hg.mozilla.org/users/florian_queze.net/purple mozilla/extensions/purple If you've set up your build environment as above, then all you need to do is: echo 'ac_add_options --enable-extensions=purple' >> .mozconfig in the comm-central directory, or just add the ac_add_options --enable-extensions=purple line to your .mozconfig with your favorite editor. Then just re-run t...
Error codes returned by Mozilla APIs
n trying to open the channel again (reopening is not supported). NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY (0x804B0022) While parsing for the first component of a header field using syntax such as that for Content-Disposition or Content-Type, the first component was found to be empty. JavaScript Errors These errors typically occur when interfacing between JavaScript and native code, or to
XPCOM components. NS_ERROR_XPC_NOT_ENOUGH_ARGS (0x80570001) NS_ERROR_XPC_NEED_OUT_OBJECT (0x80570002) NS_ERROR_XPC_CANT_SET_OUT_VAL (0x80570003) NS_ERROR_XPC_NATIVE_RETURNED_FAILURE (0x80570004) NS_ERROR_XPC_CANT_GET_INTERFACE_INFO (0x80570005) NS_ERROR_XPC_CANT_GET_PARAM_IFACE_INFO (0x80570006) NS_ERROR_XPC_CANT_GET_METHOD_INFO (0x80570007) NS_ERROR_XPC_UNEXPECTED (0x805...
... Components.results ...
Roll your own browser: An embedding how-to
build is done, you can change directory into mozilla/embedding/config, and do a make. This will produce a directory in DIST named Embed. It should include all of the base support that you need to get a web browser started up. Included is the sample test application (gtkEmbed or winEmbed). What initializations do I have to do? Somewhere during the start of your application, you must initialize
XPCOM. You will also want to shut this down when you quit. Other initialization must be done to start up event queues and load some string bundles. All of this is somewhat generic and has been isolated into a static library that you can simply call on. If you build mozilla/embedding/base/, a static library (on windows) called baseembed_s.lib is built. Just link this library to your application. There...
...been isolated into a static library that you can simply call on. If you build mozilla/embedding/base/, a static library (on windows) called baseembed_s.lib is built. Just link this library to your application. There are two functions that are needed: nsresult NS_InitEmbedding(const char *aPath); nsresult NS_TermEmbedding(); Pretty self-explanatory. The aPath parameter will be passed to NS_Init
XPCOM. NS_InitEmbedding() must be called from the main thread of your application, otherwise it won't work. Do you have any simple examples of embedding Mozilla? There are many examples of products already using Gecko for embedding. Here's a partial list. The sections marked 'Mozilla Examples' refer to clients and sample code to be found within the Mozilla source tree. Linux External projects Sa...
Sqlite.jsm
Sqlite.jsm will create, manage, and destroy statement instances for you. You don't need to worry about caching created statement instances, destroying them when you are done, etc. This translates to fewer lines of code to talk to SQLite. All operations are asynchronous. Use of synchronous Storage APIs is discouraged because they block the main thread. ...
...nsactions. Sqlite.jsm exposes a transaction API built on top of Task.jsm that allows transactions to be written as procedural JavaScript functions (as opposed to a series of callback driven operations). If the function throws, the transaction is automatically rolled back. This makes code easy to write and read. JavaScript-y API. Sqlite.jsm feels like a pure JavaScript module. The complexities of
XPCOM are mostly hidden from view. JavaScript programmers should feel right at home using Sqlite.jsm. Note: The Sqlite.jsm JavaScript code module can only be used from chrome -- that is, from within the application itself or an add-on. Before you can use this module, you need to import it into your scope: Components.utils.import("resource://gre/modules/Sqlite.jsm") Obtaining a Connection Sqlite.j...
JavaScript code modules
vides a basic standardized interface for performing in-code logical assertions with optional, customizable error reporting. BookmarkHTMLUtils.jsm Provides utility functions for importing and exporting bookmarks from the old-school "bookmarks.html" style bookmark files. ctypes.jsm Provides an interface that allows JavaScript code to call native libraries without requiring the development of an
XPCOM component. CustomizableUI.jsm Allows you to interact with customizable buttons and items in Firefox's main window UI. DeferredTask.jsm Run a task after a delay. Dict.jsm Provides an API for key/value pair dictionaries. DownloadLastDir.jsm Supplies the path to the directory into which the last download occurred. Downloads.jsm Provides a single entry point to interact with the downloading...
...operations simple, using the power of JavaScript's yield operator. Timer.jsm A pure JS implementation of window.setTimeout. Webapps.jsm Provides an interface to manage Open Web Apps. WebRequest.jsm Provides an API to add event listeners for the various stages of making an HTTP request. The event listener receives detailed information about the request, and can modify or cancel the request.
XPCOMUtils.jsm Contains utilities for JavaScript components loaded by the JS component loader. ...
Leak-hunting strategies and tips
g leaks that go through XPConnect Many large object graphs that leak go through XPConnect. This can mean there will be XPConnect wrapper objects showing up as owning the leaked objects, but it doesn't mean it's XPConnect's fault (although that has been known to happen, it's rare). Debugging leaks that go through XPConnect requires a basic understanding of what XPConnect does. XPConnect allows an
XPCOM object to be exposed to JavaScript, and it allows certain JavaScript objects to be exposed to C++ code as normal
XPCOM objects. When a C++ object is exposed to JavaScript (the more common of the two), an XPCWrappedNative object is created. This wrapper owns a reference to the native object until the corresponding JavaScript object is garbage-collected. This means that if there are leaked GC root...
...est way to solve these problems is often to simply debug the leaked JS roots. These roots are printed on shutdown in DEBUG builds, and the name of the root should give the type of object it is associated with. One of the most common ways one could leak a JS root is by leaking an nsXPCWrappedJS object. This is the wrapper object in the reverse direction -- when a JS object is used to implement an
XPCOM interface and be used transparently by native code. The nsXPCWrappedJS object creates a GC root that exists as long as the wrapper does. The wrapper itself is just a normal reference-counted object, so a leaked nsXPCWrappedJS can be debugged using the normal refcount-balancer tools. If you really need to debug leaks that involve JS objects closely, you can get detailed printouts of the paths JS ...
AsyncTestUtils extended framework
ntheticMessages held in the set. While you should not modify this list, you can get its length and read from it. getMsgHdr(aIndex) [function] Retrieve the nsIMsgDBHdr at the given index. getMsgURI(aIndex) [function] Retrieve the URI of the message header at the given index. msgHdrList [getter] Return a JS list with all the nsIMsgDbHdrs for the messages that have been injected into folders.
xpcomHdrArray [getter] Return an nsIMutableArray of the message headers that have been injected into folders. foldersWithMsgHdrs [getter] Return a list where each element is a list with two sub-elements. The first is an nsIMsgFolder and the second is a JS list of all the nsIMsgDBHdrs for the messages that were inserted into the folder. This is used by routines that need to process the messages group...
...een injected into folders. foldersWithMsgHdrs [getter] Return a list where each element is a list with two sub-elements. The first is an nsIMsgFolder and the second is a JS list of all the nsIMsgDBHdrs for the messages that were inserted into the folder. This is used by routines that need to process the messages grouped by the folder they belong to, such as initiating message moves. foldersWith
XpcomHdrArrays [getter] Same as foldersWithMsgHdrs but the second element in each sub-list is an nsIMutableArray instead of a JS list. Manipulating messages setRead(aBeRead) setRead(true) marks all the messages in the set as read, setRead(false) marks them as unread. setStarred(aBeStarred) setStarred(true) marks all the messages in the set as starred ("flagged" in IMAP parlance), setStarred(fa...
Aggregating the In-Memory Datasource
Why would you want to do this? Say you were writing a datasource2, and the way you chose to implement it was to "wrap" the in-memory datasource; i.e., MyClass : public nsIMyInterface, public nsIRDFDataSource { private: nsCOMPtr<nsIRDFDataSource> mInner; public: // nsIRDFDataSource methods NS_IMETHOD Init(const char* aURI) { return mInner->Init(aURI); } NS_IMETHOD GetURI(char* *aURI) { return mInner->GetURI(aURI); } // etc., for each method in nsIRDFDataSource! }; Very painful, prone to errors, and fragile as the interfaces are still in flux (a wee bit). Aggregation to the rescue! Here are the gory details on how. ...
...mething() { nsCOMPtr<nsIRDFDataSopurce> ds = do_QueryInterface(mInner); rv = ds->Assert(/* something useful here */); // etc... return NS_OK; } It may be tempting to keep a pointer to the aggregate's nsIRDFDataSource in a member variable, butyou can't do that. Why? Because if you did, you'd hold a circular reference that would never unwind. Notes Describing all of the vagaries of
XPCOM aggregation is beyond the scope of this document. The basic idea is to overload QueryInterface(), allowing it to return adelegate object that supports the interface. There is some trickery involved on the delegate's part to ensure that reference counting is done sanely, and that the reflexive, symmetric, and transitive properties of QueryInterface() are preserved. If you're really interested, I'd...
Generating GUIDs
Add-ons can (and should) be identified with IDs of the form extensionname@organization.tld since Firefox 1.5. Warning: If you just want an ID for your add-on, generating a GUID is almost definitely not what you want to do. Using the extensionname@organization.tld form is approximately one thousand times easier for everyone involved. Don't have a domain name? Do you have a blog on a subdomain? Use that. ...
.../usr/bin/uuidgen. Perl jkeiser's Mozilla tools include a UUID generator with output format of both C++ and IDL style. sfink's update-uuids will change the uuid for a given interface and all of its descendants, updating all *.idl files within a directory tree. nsIUUIDGenerator A UUID can be generated from privileged Mozilla code using nsIUUIDGenerator. See the linked page for details. COM/
XPCOM format When #define-ing IIDs and CIDs in Mozilla C++ code, you generally use the following format: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx #define NS_...ID \ { 0xXXXXXXXX, 0xXXXX, 0xXXXX, \ { 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX } } You can generate code in this format using one of the following tools. Online tools http://mozilla.pettay.fi/cgi-bin/mozuuid.pl guidgen guidgen.
Generic factory
Rick Potts wrote a templated-based generic factory (nsFactory<T>) that simplifies the factory creation process that just requires writing a CreateInstance() method. The new nsIGenericFactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsIFactory is needed. Here is the interface, and a description of its use. /** * Provides a Generic nsIFactory implementation that can be used by * DLLs with very simple factory needs. ...
... Background (This is based on my original news posting <beard-2402991733140001@h-198-93-95-151.mcom.com>.) We seem to be creating a huge number of different factory implementations. It seems to me that we can cut down on code size (all those QueryInterface, AddRef, Release implementations) if we just use the following class for al...
Packaging WebLock
onent Installation Overview XPInstall is a set of JavaScript APIs for creating installation scripts. Using XPInstall, you can create web-based installations for Gecko-based applications, Mozilla extensions, or individual components. The installation script for the WebLock component can also be used to register the component with the browser into which it is installed (see Registration Methods in
XPCOM for more information on registration). The sample installation script shown below uses the Mozilla XPInstall technology to manipulate an installer and talk to Mozilla'schrome registry as high-level JavaScript objects. What Is the Chrome Registry? Like the Windows registry, the chrome registry is a database of information about applications, skins, and other extensions that have been installed...
...L and say where it'll go addFile("weblock.dll", 1.0, "weblock.dll", componentsDir, ""); // add the typelib also addFile("weblock.xpt", "1.0", "weblock.xpt", componentsDir, ""); // add the weblock subdirectory of the XPI and specify that // it be installed in the chrome application directory err = addDirectory("weblock", "1.0", "", chromeDir, ""); // ? have to register component here or with reg
xpcom? // register the new UI with the mozilla chrome registry registerChrome(CONTENT, getFolder(cf,"weblock.xpi"),"weblock"); registerChrome(SKIN, getFolder(cf, "weblock.xpi"),"weblock"); // perform the installation if there are no errors if (err==SUCCESS) performInstall(); else cancelInstall(err); The WebLock Trigger Script The trigger script is the script placed on a web page that actually...
Making cross-thread calls using runnables
Each runnable represents a task which can then be dispatched to another thread for execution. ...
...llback(callback) , mDigits(digits) { } NS_IMETHOD Run() { nsCString result; CalculatePi(mDigits, result); nsCOMPtr<nsIRunnable> resultrunnable = new PiResultTask(mCallback, result); NS_DispatchToMainThread(resultrunnable); } private: PiCallback mCallback; int mDigits; }; Putting it all together To start a new thread, create it using the Thread Manager: #include "ns
XPCOMCIDInternal.h" void CalculatePiAsynchronously(int digits, PiCallback callback) { // To create a new thread, get the thread manager nsCOMPtr<nsIThreadManager> tm = do_GetService(NS_THREADMANAGER_CONTRACTID); nsCOMPtr<nsIThread> mythread; nsresult rv = tm->NewThread(0, 0, getter_AddRefs(mythread)); if (NS_FAILED(rv)) { // In case of failure, call back immediately with an empty string ...
Components.returnCode
Components.returnCode is a property which can hold an
XPCOM return code additionally to the value returned by the return statement. Note that Components.returnCode is currently non-functional due to bug 287107. This problem was introduced in Mozilla 1.4. Usage Components.returnCode is a property that can be used to indicate to an
XPCOM caller of the JavaScript method that the method is returning a specific nsresult code. Generally, XPConnect does a fine job of making it unnecessary for JavaScript code to worry about nsresult codes. By default the successful completion of the JavaScript method will cause XPConnect to return a result code of NS_OK to the caller. ...
...turning a specific nsresult code. Generally, XPConnect does a fine job of making it unnecessary for JavaScript code to worry about nsresult codes. By default the successful completion of the JavaScript method will cause XPConnect to return a result code of NS_OK to the caller. If the JavaScript code needs to signal failure then that is done by throwing an exception. However, there are a very few
XPCOM interfaces that specify success code return values. Components.returnCode exists in order to make it possible to implement these rare interfaces in JavaScript. Example var foo = { bar: function(i) { if (yada_yada) Components.returnCode = 5; return i * 2; } }; ...
Components.utils.forceGC
Components.utils.forceGC lets scripts force a garbage collection cycle. The Mozilla JavaScript engine will perform garbage collection automatically when the JavaScript heap grows beyond a certain size. This mechanism doesn't account for any native (C++)
XPCOM objects hanging off JavaScript objects though. In many cases a JavaScript application will have internal knowledge of JavaScript objects referencing large (trees of)
XPCOM objects and know when they are no longer reachable. In this case it can be important to be able to force a garbage collection cycle from JavaScript. Another instance where it can be useful to force garbage collection is before cleaning out dead reference from a hash of weak JavaScript references. Users should note that garbage collection is a very expensive operation an...
...t dead reference from a hash of weak JavaScript references. Users should note that garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. Note: nsIDOMWindowUtils.garbageCollect() offers similar functionality but will trigger the cycle collector in addition to the garbage collector in the JavaScript engine. This will make sure that
XPCOM components that build cycles with JavaScript objects also get collected which might be important, for example for testcases that depend on the garbage collector. Requires UniversalXPConnect privileges. If you want to schedule garbage collection to occur in the future, at a time when no JavaScript code is running, you can use Components.utils.schedulePreciseGC() instead. ...
Examples
The test apps can be found at mozilla/extensions/java/
xpcom/tests. ...
... ...
xpcshell
Prerequisites You need your own build of Mozilla to use xpcshell. Running xpcshell ./run-mozilla.sh ./xpcshell xpcshell is almost always in the same directory as run-mozilla.sh. ...
...not available. To rectify this, run xpcshell with the -v 180 command-line option, which tells xpcshell to use JavaScript 1.8. Example You can input JavaScript, straight to Mozilla. js> 5+7 12 js> print("Hello, world!") Hello, world! js> See also HOWTO for common problems in writing xpcshell scripts, e.g., doing async network calls or using JS modules. Pretty much all Mozilla programs use
XPCOM components via XPConnect. Read XPConnect:Using components to get started with that. See the XPCShell Reference for information on command line arguments and extension functions. Learn how to write xpcshell-based unit tests. Read XPCShell:Profiling for information on how to profile scripts. ...
XPConnect
XPConnect is a bridge between JavaScript and
XPCOM. With XPConnect, you can use
XPCOM components from JavaScript code, and interact with JavaScript objects from within
XPCOM components. XPConnect is part of Firefox and is actively used in XUL applications. Documentation Architecture basics XPConnect, JavaScript,
XPCOM, XUL... Using components How to talk with
XPCOM components. XPConnect and XPIDL FAQ A FAQ about using XPConnect and XPIDL. This page needs to migrate to MDN. ...
... XPConnect, JavaScript,
XPCOM, XUL... Using components How to talk with
XPCOM components. XPConnect and XPIDL FAQ A FAQ about using XPConnect and XPIDL. This page needs to migrate to MDN. ...
nsLocalFile
Example Code function getFileSize(path) { var file = Components.classes["@mozilla.org/file/local;1"]. ...
... Example Code function getFileSize(path) { var file = Components.classes["@mozilla.org/file/local;1"]. ...
nsObserverService
It should be used from the main thread only. ...
...It should be used from the main thread only. ...
NS_Alloc
It is equivalent to calling alloc on the nsIMemory instance returned from NS_GetMemoryManager. History This function was finalized for Mozilla 1.8. See bug 267767 for details. ...
...It is equivalent to calling alloc on the nsIMemory instance returned from NS_GetMemoryManager. History This function was finalized for Mozilla 1.8. See bug 267767 for details. ...
NS_Free
It is equivalent to calling free on the nsIMemory instance returned from NS_GetMemoryManager. History This function was finalized for Mozilla 1.8. See bug 267767 for details. ...
...It is equivalent to calling free on the nsIMemory instance returned from NS_GetMemoryManager. History This function was finalized for Mozilla 1.8. See bug 267767 for details. ...
nsACString
This class is typically used to represent ASCII or UTF-8 character arrays. #include "nsStringAPI.h" class nsACString { ... }; Typedefs char_type [char] Storage unit for this class. self_type [nsACString] An alias for the type of this class. size_type [PRUint32] Type used to represent the number of bytes stored in the string. index_type [PRUint32] Type used to represent an offset into the string. Methods BeginReading The BeginReading function returns a const pointer to the first element of the string's internal buffer. ...
...depends on the context in which it is used. If used with XPIDL, then the character encodings of the corresponding XPIDL data types applies. nsACString may even hold data with embedded null bytes. Thus, the length of the data contained in the nsACString should be determined by calling the nsACString::Length() method. The methods defined on nsACString are implemented as inline wrappers around the
XPCOM string functions, prefixed with NS_CString. See, for example, NS_CStringGetData. See also nsACString::Length() NS_CStringGetData nsEmbedCString ...
nsAString
This class is typically used to represent Unicode character arrays. #include "nsStringAPI.h" class nsAString { ... }; Typedefs char_type [PRUnichar] Storage unit for this class. self_type [nsAString] An alias for the type of this class. size_type [PRUint32] Type used to represent the number of double-byte units stored in the string. index_type [PRUint32] Type used to represent an offset into the string. Methods BeginReading The BeginReading function returns a const pointer to the first element of the string's internal buffer. ...
...stance depends on the context in which it is used. If used with XPIDL, then the character encodings of the corresponding XPIDL data types applies. nsAString may even hold data with embedded null values. Thus, the length of the data contained in the nsAString should be determined by calling the nsAString::Length method. The methods defined on nsAString are implemented as inline wrappers around the
XPCOM string functions, prefixed with NS_String. See, for example, NS_StringGetData. See Also nsAString::Length, EndReading, NS_StringGetData, nsEmbedString ...
nsEmbedCString
<<
XPCOM API Reference Summary The nsEmbedCString concrete class provides a way to construct a nsACString object that allocates null-terminated storage. #include "nsEmbedString.h" class nsEmbedCString : public nsACString { ... }; Typedefs self_type [nsEmbedCString] An alias for the type of this class. abstract_string_type [nsACString] An alias for the abstract string type this class specializes. Methods nsEmbedCString Constructors for nsEmbedCString. get The get function returns a const pointer to the string's null-terminated, internal buffer. Operators operator= This operator is a shortcut for the inherited nsACString::Assign family of functions. ...
...abstract string type this class specializes. Methods nsEmbedCString Constructors for nsEmbedCString. get The get function returns a const pointer to the string's null-terminated, internal buffer. Operators operator= This operator is a shortcut for the inherited nsACString::Assign family of functions. Remarks The methods defined on nsEmbedCString are implemented as inline wrappers around the
XPCOM string functions, prefixed with NS_CString. See, for example, NS_CStringContainerInit. See Also NS_CStringContainerInit, nsACString ...
nsEmbedString
#include "nsEmbedString.h" // Or: #include "nsStringGlue.h" if inside Gecko class nsEmbedString : public nsAString { ... }; Typedefs self_type [nsEmbedString] An alias for the type of this class. abstract_string_type [nsAString] An alias for the abstract string type this class specializes. Methods nsEmbedString Constructors for nsEmbedString. get The get function returns a const pointer to the string's null-terminated, internal buffer. Operators operator= This operator is a shortcut for the inherited nsAString::Assign family of functions. ...
... the abstract string type this class specializes. Methods nsEmbedString Constructors for nsEmbedString. get The get function returns a const pointer to the string's null-terminated, internal buffer. Operators operator= This operator is a shortcut for the inherited nsAString::Assign family of functions. Remarks The methods defined on nsEmbedString are implemented as inline wrappers around the
XPCOM string functions, prefixed with NS_String. See, for example, NS_StringContainerInit. See Also NS_StringContainerInit, nsAString ...
nsSupportsWeakReference
Example code // Supporting weak references to a hypothetical implementation // of the nsIFoo interface... ...
...ce. See Weak reference for detailed description of weak references. #include "nsWeakReference.h" class nsSupportsWeakReference { ... }; Remarks In addition to inheriting from this class, you will need to ensure that your nsISupports::QueryInterface implementation exposes nsISupportsWeakReference as a supported interface. To use this class, you must link your component or application against the
XPCOM Glue library. Example code // Supporting weak references to a hypothetical implementation // of the nsIFoo interface... #include "nsWeakReference.h" #include "nsIFoo.h" class MyFoo : public nsIFoo, public nsSupportsWeakReference { public: NS_DECL_ISUPPORTS NS_DECL_NSIFOO ... }; NS_IMPL_ISUPPORTS2(MyFoo, nsIFoo, nsISupportsWeakReference) ... See also nsISupports::QueryInte...
nsIChannel
ve a subclass of nsIChannel for protocol-specific parameters. Then, the URI can be fetched by calling open() or asyncOpen(). After a request has been completed, the channel is still valid for accessing protocol-specific results. For example, QueryInterfacing to nsIHttpChannel allows response headers to be retrieved for the corresponding http transaction. This interface must be used only from the
XPCOM main thread. Implemented by netwerk/base/src/nsBaseChannel.cpp and netwerk/protocol/http/src/nsHttpChannel.cpp. Method overview void asyncOpen(in nsIStreamListener aListener, in nsISupports aContext); nsIInputStream open(); Attributes Attribute Type Description contentCharset ACString The character set of the channel's content if ava...
...hould not call this method, because it tends to fail when a request is redirected, rather than redirecting transparentlyNote: nsIChannel implementations are not required to implement this method. Moreover, since this method may block the calling thread, it should not be called on a thread that processes UI events. Like any other nsIChannel method it must not be called on any thread other than the
XPCOM main thread. nsIInputStream open(); Parameters None. Return value Blocking input stream to the channel's data. Exceptions thrown NS_ERROR_IN_PROGRESS If the channel is reopened. See also nsIChannelEventSink for onChannelRedirect ...
nsIChromeRegistry
Converts a chrome URL into a canonical representation b...
...e://package/provider/package.ext. The extension, ext, is one of: xul For a "content" package. css For a "skin" package. dtd For a "locale" package. nsIURI convertChromeURL( in nsIURI aChromeURL ); Parameters aChromeURL The URL that is to be converted. Return value A new nsIURI object containing the loadable URI for the specified chrome URL. Violates the
XPCOM interface guidelines wrappersEnabled() Returns whether XPCNativeWrappers are enabled for the specified URI. boolean wrappersEnabled( in nsIURI aURI ); Parameters aURI The URI for which to determine if XPCNativeWrappers are enabled. Return value true if XPCNativeWrappers are enabled for the specified URI; otherwise false. See also Chrome Registration ...
nsIClassInfo
Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview nsISupports getHelperForLanguage(in PRUint32 language); void getInterfaces(out PRUint32 count, [array, size_is(count), retval] out nsIIDPtr array); Attributes Attribute Type Description classDescription string A human readable string naming the class, or null. Read only. classID nsCIDPtr A classID through which an instance of this class can be created, or null. ...
...ttribute has the SINGLETON bit set, then the value of this attribute specifies a ClassID through which this class can be accessed as a service using nsIServiceManager.getService(). This attribute is similar to the classID attribute; however, this attribute exists so that C++ callers can avoid allocating and freeing a nsCID object, as would happen if they used classID. Read only. Violates the
XPCOM interface guidelines Exceptions thrown NS_ERROR_NOT_AVAILABLE If the class does not have a ClassID contractID string A contractID through which an instance of this class can be created, or null. If the flags attribute has the SINGLETON bit set, then the value of this attribute specifies a ContractID through which this class may be accessed as a service...
nsIDOMGlobalPropertyInitializer
dom/interfaces/base/nsIDOMGlobalPropertyInitializer.idlScriptable An initializer for global properties that lets them know about the window they're being attached to. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) An
XPCOM component implementing this interface can be exposed to web content as a property on the window. See Custom window properties are a snap in Firefox blog post for details. An alternative way to expose an object to the web content is to add the property in response to the content-document-global-created notification. Method overview jsval init(in nsIDOMWindow window); Methods init() jsval init( in nsIDOMWindow window ); Parameters window T...
...e web content is to add the property in response to the content-document-global-created notification. Method overview jsval init(in nsIDOMWindow window); Methods init() jsval init( in nsIDOMWindow window ); Parameters window The window to which the global property is being attached. Return value The initialized global property. Ensure that you never return any internal
XPCOM objects to untrusted code. It is also recommended to use __exposedProps__ to control which members are exposed. ...
nsIDOMParser
a web developer, please refer to the DOMParser documentation instead. Creating a DOMParser To create a DOMParser object from a web page or a chrome script running in a window, simply use new DOMParser(). When you create a DOMParser from a privileged script, you can pass parameters to the constructor, more on that below. To create a DOMParser when the constructor is not available (e.g., from a JS
XPCOM component, a JS module, or an xpcshell test), use: var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"] .createInstance(Components.interfaces.nsIDOMParser); // optionally, call parser.init(principal, documentURI, baseURI); Principals, document and base URI Note: This section covers changes introduced to DOMParser in Gecko 1.9. (This section is only relevant to Firef...
...privileged code will be able to access (see discussion in bug 565480). Parsing a string Once you've created a DOMParser object, you can use its parseFromString method to parse XML or HTML as described in the Web platform documentation. ...
nsIDebug
xpcom/base/nsIDebug.idlScriptable Provides debugging support for scripted languages, such as JavaScript, Java, Python, Perl, and so forth. Inherits from: nsISupports Last changed in Gecko 1.7 Note: C/C++ consumers who are planning to use the nsIDebug interface with the @mozilla.org/
xpcom;1 contract should use NS_DebugBreak() from
XPCOM glue instead, or alternatively the NS_ABORT, NS_ASSERTION, NS_BREAK, and NS_WARNING macros, which also call NS_DebugBreak() if used in a debugging build. Method overview void abort(in string aFile, in long aLine); void assertion(in string aStr, in string aExpr, in string aFile, in long aLine); void break(in string aFile, in long aLine); void warning(in string aStr, in string aFile, in long aLine); Methods abort() Requests the process t...
...ong aLine); void break(in string aFile, in long aLine); void warning(in string aStr, in string aFile, in long aLine); Methods abort() Requests the process to trigger a fatal abort. void abort( in string aFile, in long aLine ); Parameters aFile File containing abort request. aLine Line number of abort request. assertion() Shows an assertion and triggers optional behavior based on the
XPCOM_DEBUG_BREAK environment variable, defaulting to calling break() on Windows and OS/2 and warning on other platforms. void assertion( in string aStr, in string aExpr, in string aFile, in long aLine ); Parameters aStr assertion message. aExpr Expression that failed. aFile File containing assertion. aLine Line number of assertion. break() Requests the software break into a debugger. If no ...
nsIDebug2
This is normally zero in release builds, but does include calls to nsIDebug.assertion(). Read only. isDebugBuild boolean Whether
XPCOM was compiled with DEBUG defined. This often correlates to whether other code (for example, Firefox, XULRunner) was compiled with DEBUG defined. Read only. ...
...This often correlates to whether other code (for example, Firefox, XULRunner) was compiled with DEBUG defined. Read only. See also nsIDebug ...
nsIDirectoryServiceProvider2
Inherits from: nsIDirectoryServiceProvider Last changed in Gecko 0.9.6 Method overview nsISimpleEnumerator getFiles(in string prop); Methods getFiles() The directory service calls this when it gets a request for a prop and the requested type is nsISimpleEnumerator. nsISimpleEnumerator getFiles( in string prop ); Parameters prop The symbolic name of the file list. Return value An enumerator for a list of file locations. The elements in the enumeration are nsIFile. Use an
XPCOM return code of NS_SUCCESS_AGGREGATE_RESULT if this result should be aggregated with other "lower" providers. ...
... nsISimpleEnumerator getFiles(in string prop); Methods getFiles() The directory service calls this when it gets a request for a prop and the requested type is nsISimpleEnumerator. nsISimpleEnumerator getFiles( in string prop ); Parameters prop The symbolic name of the file list. Return value An enumerator for a list of file locations. The elements in the enumeration are nsIFile. Use an
XPCOM return code of NS_SUCCESS_AGGREGATE_RESULT if this result should be aggregated with other "lower" providers. If you are implementing this from JS, you would be using Components.returnCode, but sadly this does not currently work (see bug 287107). ...
nsIEditor
<<
XPCOM API Reference editor/nsIEditor.idlScriptable Provides methods and attributes used when editing page content. 66 Introduced Gecko 1.0 Inherits from: nsISupports Last changed in Gecko 18.0 (Firefox 18.0 / Thunderbird 18.0 / SeaMonkey 2.15) Method overview [noscript] void init(in nsIDOMDocument doc, in nsIContent aRoot, in nsISelectionController aSelCon, in unsigned long aFlags); void setAttributeOrEquivalent(in nsIDOMElement element, in AString sourceAttrName, in AString sourceAttrValue, in boolean aSuppressTransaction); void removeAttributeOrEquivalent(in nsIDOMElement element, in DOMString sourceAttrName, in boolean aSuppressTransaction); void postCreate(); void preDestroy(in boolean aDestroyingFrames); ...
...veEditActionListener(in nsIEditActionListener listener); void addDocumentStateListener(in nsIDocumentStateListener listener); void removeDocumentStateListener(in nsIDocumentStateListener listener); Debug Methods void dumpContentTree(); void debugDumpContent() ; void debugUnitTests(out long outNumTests, out long outNumTestsFailed); [not
xpcom] boolean isModifiableNode(in nsIDOMNode aNode); Constants Load Flags Constant Value Description eNone 0 eNext 1 ePrevious 2 eNextWord 3 ePreviousWord 4 eToBeginningOfLine 5 eToEndOfLine 6 Attributes Attribute Type Descriptio...
nsIFile
Inherits from: nsISupports Last changed in Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27) nsIFile is the correct platform-agnostic way to specify a file; you should always use this instead of a string to ensure compatibility. With an nsIFile you can navigate to ancestors or descendants without having to deal with the different path separators used on different platforms, query the state of any file or directory at the position represented by the nsIFile and create, move or copy items in the filesystem. ...
...d). On Win32 platforms, it is the currently selected ANSI codepage (specified by CP_ACP). The word "Native" appears in the name of methods that operate on or return strings encoded in the native character set. A string containing characters encoded in the native character set cannot be safely passed to JavaScript via XPConnect. Therefore, the "native" methods and attributes are not scriptable.
XPCOM provides the string conversion functions NS_CStringToUTF16 and NS_UTF16ToCString, which can be used to convert a string between UTF-16 and the native character encoding. This interface was frozen for Gecko 1.0. See bug 129279 for details. From Gecko 2.0 interfaces are no longer frozen. See also nsILocalFile NS_CStringToUTF16 NS_UTF16ToCString ...
nsIINIParser
Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Typically, you'll create an nsIINIParser object by calling nsIINIParserFactory.createINIParser(). Also, if you need to write to an INI file, use nsIINIParserWriter. nsIUTF8StringEnumerator getKeys(in AUTF8String aSection); nsIUTF8StringEnumerator getSections(); AUTF8String getString(in AUTF8String aSection, in AUTF8String aKey); Methods getKeys() Returns an nsIUTF8StringEnumerator providing the keys available within the specified section of the INI file. ...
...ction in the ini file. INI sections are * defined by square brakets and look like this: [Settings] * All entries below such a section definition belong to that * section (until the next section). * @param {String} prop * The name of the property to get. */ function getIniValue (iniFile, section, prop) { var iniFact = Components.manager.getClassObjectByContractID( "@mozilla.org/
xpcom/ini-parser-factory;1", Components.interfaces.nsIINIParserFactory ); var iniParser = iniFact.createINIParser(iniFile); try { return iniParser.getString(section,prop); } catch(e) { return undefined; } } // Usage: var lang = getIniValue(file,"Setting","Language"); Enumerating sections This example gets a list of all the sections in the INI file. // get all sections in the i...
nsIINIParserFactory
1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) See Example for how to use this interface. Method overview nsIINIParser createINIParser(in nsILocalFile aINIFile); Methods createINIParser() Creates an INI parser, returning the nsIINIParser object that you can use to parse it. nsIINIParser createINIParser( in nsILocalFile aINIFile ); Parameters aINIFile The INI file to parse. Return value The nsIINIParser object you can use to parse the INI file. ...
...er instance for an INI file, you may use the following code: // create an nsILocalFile var cl = "@mozilla.org/file/local;1"; var interf = Components.interfaces.nsILocalFile; var file = Components.classes[cl].createInstance(interf); // init the file with the path to your ini file var path = "c:\\temp\\example.ini"; file.initWithPath(path); // create the nsIINIParserFactory var cl = "@mozilla.org/
xpcom/ini-parser-factory;1"; var interf = Components.interfaces.nsIINIParserFactory; var iniFact = Components.manager.getClassObjectByContractID(cl,interf); // get the INIParser for the ini file var iniParser = iniFact.createINIParser(file); See also nsIINIParser nsILocalFile ...
nsIINIParserWriter
1.0 66 Introduced Gecko 1.9.2 Inherits from: nsISupports Last changed in Gecko 13.0 (Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10) This interface provides methods that allow writing to INI-format configuration files. INI files contain zero or more sections, denoted by a name in square brackets, followed by zero or more lines of text with a property name on the left, then an equals sign ("="), then the value of the property. ...
...denoted by a name in square brackets, followed by zero or more lines of text with a property name on the left, then an equals sign ("="), then the value of the property. To create an nsIINIParserWriter object, you use the nsIINIParserFactory interface to create a parser, then nsISupports.QueryInterface() that to get an nsIINIParserWriter, like this: let writer = Components.classes["@mozilla.org/
xpcom/ini-processor-factory;1"]. .getService(Components.interfaces.nsIINIParserFactory) .createINIParser(someLocalFile) .QueryInterface(Components.interfaces.nsIINIParserWriter); Here, someLocalFile is an nsIFile based object, such as an nsILocalFile. This indicates the file into which the INI data will be written. Once the writer ...
nsIInProcessContentFrameMessageManager
Return value The nsIContent object representing the owner's content. See also Content process event handling nsIContentFrameMessageManager ...
...Return value The nsIContent object representing the owner's content. See also Content process event handling nsIContentFrameMessageManager ...
nsIJSID
The first two cases create a named JSID while the last two cases create an unnamed JSID. An unnamed JSID also results when you implement a function that is passed an nsIIDRef parameter, such as QueryInterface(). Note that for these cases of JSID the specified class or interface must exist and be scriptable. Method overview boolean equals(in nsIJSID other); const nsID* getID(); Violates the
XPCOM interface guidelines void initialize(in string idString); string toString(); Attributes Attribute Type Description id nsIDPtr Read only. Native code only! Obsolete since Gecko 1.9 The internal nsID. name string Read only. The name of the JSID, if it was set. number string Read only. The string representation of the internal nsID. valid boolean Read only. Returns true if the JSI...
...epresentation of the internal nsID. valid boolean Read only. Returns true if the JSID has been initialised. Methods equals() This method determines if this nsIJSID has the same nsID as another nsIJSID. boolean equals( in nsIJSID other ); Parameters other The other nsIJSID to compare to. Return value true if the nsIJSID's are valid and have the same nsID, otherwise false. Violates the
XPCOM interface guidelines getID() const nsID* getID(); Parameters None. Return value A pointer to the internal nsID structure. initialize() Initializes the JSID. void initialize( in string idString ); Parameters idString The number to initialize the JSID, in string format, e.g. {00000000-0000-0000-c000-000000000046}. A JSID can only be initialized once. toString() This methods returns a stri...
nsIMemory
Inherits from: nsISupports Last changed in Gecko 0.9.6 nsIMemory is used to allocate and deallocate memory segments from a heap. The implementation is free to define the heap. NS_GetMemoryManager returns the global nsIMemory instance. Method overview voidPtr alloc(in size_t size); Violates the
XPCOM interface guidelines void free(in voidPtr ptr); Violates the
XPCOM interface guidelines void heapMinimize(in boolean immediate); boolean isLowMemory(); Deprecated since Gecko 2.0 voidPtr realloc(in voidPtr ptr, in size_t newSize); Violates the
XPCOM interface guidelines Methods alloc Allocates a block of memory of a particular size. ...
... voidPtr alloc( in size_t size ); Parameters size The size of the block to allocate. ...
nsIObserver
These notifications are often, though not always, broadcast via the nsIObserverService. Inherits from: nsISupports Last changed in Gecko 0.9.6 Method overview void observe(in nsISupports aSubject, in string aTopic, in wstring aData); Methods observe() This method will be called when there is a notification for the topic that the observer has been registered for. If you expect multiple topics/subjects, the implementor is responsible for filtering. You should not modify, add, remove, or enumerate notifications in the implementation of this method. ...
... implementation can observe multiple types of notification, and is responsible for dispatching its own behavior on the basis of the parameters for a given callback. In general, aTopic is the primary criterion for such dispatch; nsIObserver implementations should take care that they can handle being called with unknown values for aTopic. The most common implementation of nsIObserverService is the
XPCOM observer service. With this implementation, it's safe (and common practice) for an implementation of nsIObserver to remove itself as an observer during the Observe callback, or to add or remove other observers. Be careful, though, because other uses of nsIObserver may not support these operations correctly within Observe. Example The following code is an implementation of nsIObserver that is re...
nsIObserverService
Inherits from: nsISupports Last changed in Gecko 0.9.6 The
XPCOM nsObserverService implements this interface to provide global notifications for a variety of subsystems. ...
...
xpcom/ds/nsIObserverService.idlScriptable This interface provides methods to add, remove, notify, and enumerate observers of various notifications. Inherits from: nsISupports Last changed in Gecko 0.9.6 The
XPCOM nsObserverService implements this interface to provide global notifications for a variety of subsystems. Implemented by @mozilla.org/observer-service;1 as a service: var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); Method overview void addObserver( in nsIObserver anObserver, in string aTopic, in boolean ownsWeak); nsISimpleEnumerator enumerateObservers( in string aTopic ); void notifyObservers( in nsISupports aSubject, in string aTopic...
nsIPropertyBag
Inherits from: nsISupports Last changed in Gecko 1.0 Method overview nsIVariant getProperty(in AString name); Attributes Attribute Type Description enumerator nsISimpleEnumerator Get a nsISimpleEnumerator whose elements are nsIProperty objects. Read only. Methods getProperty() Get a property value for the given name. nsIVariant getProperty( in AString name ); Parameters name The name to return the matching property. Return value The property matching the given name. Exceptions thrown NS_ERROR_FAILURE If a property with that name doesn't exist. ...
...een Windows XP, Vista, 7, etc. To do this use nsIPropertyBag: Services.sysinfo.getProperty("version"); //output 5.1 Services.sysinfo.getProperty("name"); //output Windows_NT Services.sysinfo.getProperty("arch"); //output x86 Services.sysinfo.getProperty("hasWindowsTouchInterface"); //outputs false or true if windows touch is there Consult the UXP Repo (//github.com/RealityRipple/UXP/blob/master/
xpcom/base/nsSystemInfo.cpp) for the properties supported. Also pay attention to their platform-specific meaning (e.g. on Android there is version and kernel_version). ...
nsIScriptableIO
ptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative
XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. nsIScriptableIO provides a convenient API for creating files and streams, as well as for r...
...e details about how to use this object, see the File and Stream Guide. network/base/public/nsIScriptableIO.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsISupports A scriptable IO object can be used in an extension or chrome code by referring to the global IO object. ...
nsISelection
??. ...
...he given nsIDOMNode. When the selection is collapsed(), and the content is focused and editable, the caret will blink there. void collapse( in nsIDOMNode parentNode, in long offset ); Parameters parentNode The given nsIDOMNode where the selection will be set. offset Where in the given dom node to place the selection (the offset into the given node). collapsed() [noscript,not
xpcom,nostdcall] boolean collapsed(); Native code only!collapseNative void collapseNative( in nsINode parentNode, in long offset ); Parameters parentNode offset collapseToEnd() Collapses the whole selection to a single point at the end of the current selection (regardless of direction). If content is focused and editable, the caret will blink there. void collapseToEnd(); Parameters No...
nsISupports
Last changed in Gecko 1.0 Method overview nsrefcnt AddRef();Violates the
XPCOM interface guidelines void QueryInterface(in nsIIDRef uuid, [iid_is(uuid),retval] out nsQIResult result); nsrefcnt Release();Violates the
XPCOM interface guidelines Methods Violates the
XPCOM interface guidelines AddRef() Notifies the object that an interface pointer has been duplicated. nsrefcnt AddRef(); Parameters None. Return value An integer value that is generally ignored. QueryInterface() The QueryInterface method provides runtime type discovery. ...
...ded. QueryInterface is a symmetric, transitive, and reflexive operator. void QueryInterface( in nsIIDRef uuid, [iid_is(uuid),retval] out nsQIResult result ); Parameters uuid The uuid of the requested interface result The resulting interface pointer. Exceptions thrown NS_ERROR_NO_INTERFACE The requested interface is not available. Violates the
XPCOM interface guidelines Release() Notifies the object that an interface pointer has been destroyed and any resources the object held on behalf of the client can be released. nsrefcnt Release(); Parameters None. Return value An integer value that is generally ignored. Remarks The method descriptions above were taken from Essential COM by Don Box. The point of those descriptions is to highlight th...
nsIWebProgressListener
the WebProgress, use // the outerWindowID. This can be communicated back down to the content // in order to do send a command to a particular DOM Window. ...
...ommunicated back down to the content // in order to do send a command to a particular DOM Window. ...
nsIWindowWatcher
-level windows, and allows some operations on them. Inherits from: nsISupports Last changed in Gecko 0.9.6 Usage notes: This component has an activeWindow property. Clients may expect this property to be always current, so to properly integrate this component the application will need to keep it current by setting the property as the active window changes. This component should not keep a (
XPCOM) reference to any windows; the implementation will claim no ownership. Windows must notify this component when they are created or destroyed, so only a weak reference is kept. Note that there is no interface for such notifications (not a public one, anyway). This is taken care of both in Mozilla and by common embedding code. Embedding clients need do nothing special about that requirement. This ...
...und into multiple arguments (but not recursively!). Can be null, in which case the window.arguments property will not be set on the new window. As of Gecko 1.9 alpha 1, can also be an nsIArray instead. Return value An nsIDOMWindow for the opened window. ...
nsIXULRuntime
1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Implemented by: @mozilla.org/xre/app-info;1. To get an instance, use: var xulRuntime = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULRuntime); Method overview void invalidateCachesOnRestart(); Attributes Attribute Type Description accessibilityEnabled boolean If true, the accessibility service is running. Read only. ...
... processID unsigned long The system process ID of the caller's process. Read only. processType unsigned long The type of the caller's process. Returns one of process type constants. Read only. widgetToolkit AUTF8String A string tag identifying the target widget toolkit in use. This is taken from the MOZ_WIDGET_TOOLKIT configure variable. Read only.
XPCOMABI AUTF8String A string tag identifying the binary ABI of the current processor and compiler vtable. This is taken from the TARGET_
XPCOM_ABI configure variable. It may not be available on all platforms, especially unusual processor or compiler combinations. The result takes the form <processor>-<compilerABI>, for example: x86-msvc ppc-gcc3. This value should almost always be u...
NS_CStringContainerInit2
#include "nsStringAPI.h" nsresult NS_CStringContainerInit2( nsCStringContainer& aContainer, const char* aData = nsnull, PRUint32 aDataLength = PR_UINT32_MAX, PRUint32 aFlags = 0 ); Parameters aContainer [in] The nsCStringContainer instance to initialize. aData [in] An array of characters used to initialize the string object. This parameter may be null. aDataLength [in] An optional parameter that specifies the length of the array pointed to by aData. Pass PR_UINT32_MAX to indicate that aData's length may be determined by scanning the string for a terminating null. If aData is null, then this parameter is ignored. ...
...e passed in data pointer directly. The caller must ensure that the data is valid for the lifetime of the string container. This flag should not be combined with NS_CSTRING_CONTAINER_INIT_ADOPT. NS_CSTRING_CONTAINER_INIT_ADOPT Data passed into NS_CStringContainerInit2 is not copied. Instead, the string takes ownership over the data pointer. The caller must have allocated the data array using the
XPCOM memory allocator. This flag should not be combined with NS_CSTRING_CONTAINER_INIT_DEPEND. NS_CSTRING_CONTAINER_INIT_SUBSTRING Data passed into NS_CStringContainerInit2 is a substring that is not null-terminated. Return Values The NS_CStringContainerInit function returns NS_OK if successful. Otherwise, it returns an error code. Remarks After a nsCStringContainer object has been initialized...
nsGetModuleProc
aLocation [in] The location of the module if any. May be null. aResult [out] The nsIModule instance. ...
... aLocation [in] The location of the module if any. May be null. aResult [out] The nsIModule instance. ...
The Thread Manager
Application/Extension JavaScript should consider using a ChromeWorker instead.") Interfaces There are several interfaces that provide threading support: nsIThreadManager The Thread Manager itself lets you create threads. nsIThread The nsIThread interface encapsulates an operating system thread, providing easy cross-platform access to multithreading in your code. ...
...ads. nsIThread The nsIThread interface encapsulates an operating system thread, providing easy cross-platform access to multithreading in your code. nsIThreadPool A thread pool provides a limited set of worker threads. When you dispatch an event to the pool, the pool selects an available worker thread to process the event. nsIThreadInternal A subclass of nsIThread that is implemented by the
XPCOM thread object to add support for observing dispatch activity on a thread. nsIThreadObserver Provides the ability to monitor a thread, to receive notifications when events are dispatched to it and when they're finished being processed. nsIThreadEventFilter This interface is used by the nsIThreadInternal.pushEventQueue() method in nsIThreadInternal to allow event filtering. nsIRunnable This i...
Index
derbird can sometimes appear confusing when you're just beginning to look at it. As such, I've always thought it would be nice to have a list of what xul, js, or other files are that are here, what they do, and where they overlay at different points within the client. Things appear confusing for several reasons: 45 Message Interfaces Interfaces, Interfaces:Scriptable, NeedsContent,
XPCOM API Reference, thunderbird nsIMsgHdr - this interface describes headers for all mail messages. It can be used to retrieve address, subject and related header information for a mail message. 46 Message examples thunderbird No summary! 47 Message list examples thunderbird No summary! 48 Message list interfaces thunderbird No summa...
..., in many cases you only need to learn a few concepts to write an extension. 74 Building a Thunderbird extension 1: introduction Add-ons, Extensions, thunderbird Thunderbird is a community managed open-source email application. It shares many of the technologies used by Mozilla Firefox, including JavaScript, the Gecko layout engine, the XUL XML User Interface Language and the
XPCOM Cross-Platform Component Object Model. Similar to Firefox, Thunderbird functionality can be enhanced and customized via extensions. 75 Building a Thunderbird extension 2: extension file layout Extensions, thunderbird Extensions are packaged and distributed in archive files (also known as Bundles), with the XPI (pronounced "zippy") file extension. At a minimum, they contain an...
Building a Thunderbird extension 1: introduction
Similar to Firefox, Thunderbird functionality can be enhanced and customized via extensions. Warning: This content is for older versions of Thunderbird. Much of it may no longer be relevant. See developer.thunderbird.net for newer information. ...
...also known as an Integrated Development Environment). These provide features like syntax highlighting and code coloration, indentation, auto-complete, etc. File archive utility: Any utility that is capable of creating archive files can be used. There are also a number of extension and applications that are useful for testing and debugging Thunderbird extensions, such as JavaScript consoles and
XPCOM inspectors. These are described on the page "Setting up an extension development environment". Documentation Thunderbird extensions (documentation overview) Firefox addons developer guide (many topics are applicable to Thunderbird) Mozilla cross-reference source code browser ("comm-central" contains the Thunderbird code repository) Community The Thunderbird development community has a ma...
Get Thunderbird version
On Thunderbird version 3.0b3pre and later, you can use the following snippet to get the Thunderbird version. ...
... var version; if ( "@mozilla.org/xre/app-info;1" in Components.classes ) version = Components.classes["@mozilla.org/xre/app-info; 1"].getService(Components.interfaces.nsIXULAppInfo).version; else version = Components.classes["@mozilla.org/preferences-service; 1"].getService(Components.interfaces.nsIPrefBranch).getCharPref ("app.version"); var versionChecker = Components.classes["@mozilla.org/
xpcom/version- comparator;1"].getService(Components.interfaces.nsIVersionComparator); if ( versionChecker.compare( version, "3.0b3" ) >= 0 ) // code for >= 3.0b3 else // code for < 3.0b3 ...
js-ctypes
tion and extension code to call back and forth to native code written in C. C++ support is possible through vtable pointers see Using COM from js-ctypes. For a discussion on extended C++ support see bug 505907. Other work made possible by js-ctypes is JNI, this is elaborated on in the JNI.jsm section and not the js-ctypes section due to the JSM abstracting away all of the js-ctypes. Unlike binary
XPCOM components, it allows developers to ship a single binary for use with multiple versions of Firefox. Note: js-ctypes is only available from chrome code; that is, ctypes is not available to websites, only application and extension code. Documentation If you are brand new to js-ctypes, and have no idea about it, the pages you should read first is - ctypes.open followed by Standa...
...feature in Firefox. ...
window.dump() - Web APIs
process was started with the -console option. If the -console option was not specified then the output goes to stderr. Output from dump() is not sent to the Browser Console. Output can be sent to the Browser Console using console.log(). Privileged code can also use Components.utils.reportError and nsIConsoleService to log messages to the Error Console/Browser Console. dump() is also available to
XPCOM components implemented in JavaScript, even though window is not the global object in components. It is also explicitly made available in sandboxes. However, this use of dump is not affected by the preference mentioned below -- it will always be shown. It is therefore advisable to either check this preference yourself or use a debugging preference of your own to make sure you don't send lots of de...
...plicitly made available in sandboxes. However, this use of dump is not affected by the preference mentioned below -- it will always be shown. It is therefore advisable to either check this preference yourself or use a debugging preference of your own to make sure you don't send lots of debugging content to a user's console when they might not be interested in it at all. Note that dump output from
XPCOM components goes to stderr, while dump called elsewhere will output to stdout. In Gecko dump() is disabled by default - it doesn't do anything but doesn't raise an error either. To see the dump output you have to enable it by setting the preference browser.dom.window.dump.enabled to true. You can set the preference in about:config or in a user.js file. Note: this preference is not listed in about...
Private Properties - Archive of obsolete content
if it has a reference to an instance of Point and its internal namespace. Keeping the namespace hidden from all functions, except members of Point, effectively implements private properties. Moreover, because members of Point have a reference to the internal namespace, they can access private properties on other instances of Point. Namespaces in the Add-on SDK The Add-on SDK is built on top of
XPCOM, the interface between JavaScript and C++ code. Since
XPCOM allows the user to do virtually anything, security is very important. Among other things, add-ons should not be able to access variables that are supposed to be private. The SDK uses namespaces internally to ensure this. As always with code that is heavily reused, the SDK defines a helper function to create namespaces. It's defined in th...
io/file - Archive of obsolete content
users run it on Unix-like systems. Likewise, if your add-on uses literal Unix-style path specifications, it won't work for users on Windows. To ensure your add-on works for everyone, generate paths using the join function. Unfortunately this API does not currently provide a way to obtain an absolute base path which you could then use with join. For now, you need to require("chrome") and use the
XPCOM directory service as described in this article about File I/O. Note that if you do decide to hardcode Windows-style paths, be sure to escape backslashes in strings. For example, to specify the file at C:\Users\Myk, you need to use the string "C:\\Users\\Myk", not "C:\Users\Myk". Read more about escaping characters in strings. Globals Functions basename(path) The path parameter must be an a...
loader/sandbox - Archive of obsolete content
ox"); let scope = sandbox('http://example.com'); The argument passed to the sandbox defines its privileges. The argument may be: a URL string, in which case the sandbox will get the same privileges as a script loaded from that URL a DOM window object, to inherit privileges from the window being passed. omitted or null: then the sandbox will have chrome privileges giving it access to all the
XPCOM components. Optionally the sandbox function can be passed a second argument (See sandbox documentation on MDN for details). Evaluate code Module provides evaluate function that lets you execute code in the given sandbox: evaluate(scope, 'var a = 5;'); evaluate(scope, 'a + 2;'); //=> 7 More details about evaluated script may be passed via optional arguments that may improve exception reporti...
system/runtime - Archive of obsolete content
these constants: Constant Value Description PROCESS_TYPE_DEFAULT 0 The default (chrome) process. PROCESS_TYPE_PLUGIN 1 A plugin subprocess. PROCESS_TYPE_CONTENT 2 A content subprocess. PROCESS_TYPE_IPDLUNITTEST 3 An IPDL unit testing subprocess. widgetToolkit A string identifying the target widget toolkit in use.
XPCOMABI A string identifying the ABI of the current processor and compiler vtable. This string takes the form <processor>-<compilerABI>, for example: "x86-msvc" or "ppc-gcc3". ...
Low-Level APIs - Archive of obsolete content
dlefish The SDK's module loader. loader/sandbox Create JavaScript sandboxes and execute scripts in them. net/url Enables you to read content from a URI. net/xhr Provides access to XMLHttpRequest functionality. places/bookmarks Create, modify, and retrieve bookmarks. places/favicon Helper functions for working with favicons. places/history Access the user's browsing history. platform/
xpcom Implement
XPCOM objects, factories, and services. preferences/event-target Listen to changes to the Preferences system in Firefox. preferences/service Access the Preferences system in Firefox. remote/child Enables an SDK module loaded into a child process to access web content in the child process and communicate with modules in the main process. remote/parent Enables you to load...
package.json - Archive of obsolete content
x; it's not available when using jpm. The full name of the package. It can contain spaces. If this key is present, its value will be used as the add-on's em:name element in its install.rdf. harnessClassID Note: This is deprecated along with cfx; it's not available when using jpm. String in the GUID format. This is used as a classID of the "harness service"
XPCOM component. Defaults to a random GUID generated by cfx. hasEmbeddedWebExtension New in jpm 1.2.0. Boolean value: true if the add-on contains an embedded WebExtension. homepage The URL of the add-on's website. This value will be used as the add-on's em:homepageURL element in its install.rdf. icon The path to an image...
Chrome Authority - Archive of obsolete content
require entry, the manifest will not include that entry, and (once the implementation is complete) the runtime code will get an exception. For example, none of the following code will be matched by the manifest scanner, leading to exceptions at runtime, when the require() call is prohibited from importing the named modules: // all of these will fail! var xhr = require("x"+"hr"); var modname = "
xpcom"; var
xpcom = require(modname); var one = require("one"); var two = require("two"); The intention is that developers use require() statements for two purposes: to declare (to security reviewers) what sorts of powers the module wants to use, and to control how those powers are mapped into the module's local namespace. Their statements must therefore be clear and easy to parse. A future manifest ...
Developing for Firefox Mobile - Archive of obsolete content
Supported io/text-streams Supported lang/functional Supported lang/type Supported loader/cuddlefish Supported loader/sandbox Supported net/url Supported net/xhr Supported places/bookmarks Not supported places/favicon Not supported places/history Not supported platform/
xpcom Supported preferences/service Supported stylesheet/style Supported stylesheet/utils Supported system/environment Supported system/events Supported system/runtime Supported system/unload Supported system/xul-app Supported tabs/utils Supported test/assert Supported tes...
Tutorials - Archive of obsolete content
oses. Creating reusable modules Structure your add-on in separate modules to make it easier to develop, debug, and maintain. Create reusable packages containing your modules, so other add-on developers can use them too. Unit testing Writing and running unit tests using the SDK's test framework. Chrome authority Get access to the Components object, enabling your add-on to load and use any
XPCOM object. Creating event targets Enable the objects you define to emit their own events. Listen for load and unload Get notifications when your add-on is loaded or unloaded by Firefox, and pass arguments into your add-on from the command line. Using third-party modules (jpm) Install and use additional modules which don't ship with the SDK itself. Localization Writing localizable cod...
Dialogs and Prompts - Archive of obsolete content
rd "Open File"/"Save File"/"Select Folder" dialogs nsIFilePicker Prompts and the prompt service Now that you understand dialogs, let's examine prompts. Prompts differ from dialogs in that they don't require custom XUL. Because of this, however, they are less customizable. Most web developers are familiar with the alert() function: This is a prime example of a prompt. nsIPromptService is an
XPCOM interface available to C++ and chrome JavaScript code (not to web pages' JS), that provides methods for displaying a few simple types of dialogs. Refer to the interface documentation for documentation and sample code. For file/folder picker dialogs, see nsIFilePicker. Original version The original version of this tutorial was written by "Ihoss" (it was here). Links nsIPromptService Open a...
Downloading Files - Archive of obsolete content
bBrowserPersist(); // Obtain the privacy context of the browser window that the URL // we are downloading comes from. If, and only if, the URL is not // related to a window, null should be used instead. ...
JavaScript Debugger Service - Archive of obsolete content
Obsolete since Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30) This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. In Firefox versions prior to Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30), the JavaScript Debugger Service (or simply JSD) used to be an
XPCOM component that allows the tracking of JavaScript while it was being executed in the browser. However, JSD has been removed in favor of the Debugger API. See the tracking bug bug 800200 for more details. Snippets Acquiring the service We acquire the service by calling the
XPCOM object. var jsd = Components.classes["@mozilla.org/js/jsd/debugger-service;1"] .getService(Components.interfaces.jsdIDebugge...
Running applications - Archive of obsolete content
There are two ways to run programs. Using nsIProcess The recommended way is to use the nsIProcess interface because it is crossplatform. Using nsILocalFile.launch() This method is not implemented on all platforms, especially not on Unix/Linux! See nsILocalFile.launch() for details and make sure that all your target platforms support this method! This method has the same effect as if you double-clicked the file, so for executable files--it will just run the file without any parameters. For more information on nsIFile/nsILocalFile, see File I/O. ...
Custom about: URLs - Archive of obsolete content
en navigate to about:myaboutpage'; // const ABOUTPAGE_URI = 'chrome://myaboutaddon/content/index.html'; class AboutPage { static get classID() { return Components.ID(`{${ABOUTPAGE_ID}}`); } static get classDescription() { return ABOUTPAGE_DESCRIPTION; } static get contractID() { return `@mozilla.org/network/protocol/about;1?what=${ABOUTPAGE_WORD}`; } static get QueryInterface() { return
XPCOMUtils.generateQI([Ci.nsIAboutModule]); } constructor() { Object.freeze(this); } getURIFlags(aURI) { return Ci.nsIAboutModule.ALLOW_SCRIPT; } newChannel(aURI, aSecurity_or_aLoadInfo) { let channel; if (Services.vc.compare(Services.appinfo.version, '47.*') > 0) { const uri = Services.io.newURI(ABOUTPAGE_URI, null, null); // greater than or equal to firefo...
Inline options - Archive of obsolete content
DDON@MY_DOMAIN") { var doc = aSubject; var control = doc.getElementById("myaddon-pref-control"); control.value = "test"; } } }; Services.obs.addObserver(observer, "addon-options-displayed", false); // Don't forget to remove your observer when your add-on is shut down. This code should be in bootstrap.js (within the startup() function) for restartless extensions or in an
XPCOM component or a JavaScript code module (not an overlay!) for traditional extensions. Note: Starting in Gecko 13.0, you can also listen for the addon-options-hidden notification, which has the same subject and data as above, to find out when the UI is about to be removed. Use this notification to remove event listeners, or any other references that might otherwise be leaked. Locating the option...
Jetpack Processes - Archive of obsolete content
process communicates with them via the nsIJetpack interface. Note: The Jetpack service, provided by nsIJetpackService, is not included by default in Firefox 4. Prior to Firefox 12, it could be included in custom builds by using ENABLE_JETPACK_SERVICE at compile time. However, the service has been removed entirely as of Firefox 12. These processes are relatively lightweight, do not have access to
XPCOM, and can innately do little other than compute. Messaging facilities that allow them to communicate with their parent chrome process are the only means by which they can be endowed with any real power. Note: The above statement is not currently true, as js-ctypes is now provided to Jetpack processes as of bug 588563. A mechanism to optionally disable this feature has been proposed in bug 614351. ...
Chapter 1: Introduction to Extensions - Archive of obsolete content
es the look of the browser) No Yes Let's build an extension Table 1 shows the various customization options available to a user in Firefox. Users have flexible customization options, using CSS in user style sheets and JavaScript/DOM in user scripts (these depend on Stylish, GreaseMonkey, and userChrome.js). In addition to CSS and JavaScript, extensions can take advantage of XUL and
XPCOM technologies for more sophisticated features. Themes, which alter Firefox's appearance, are a kind of add-on. In order to create an extension, you need an idea and just a little programming ability. The following chapters explain in detail the extension-writing techniques of some of Japan's leading extension authors. We encourage you to try your hand at it as well. 1 One of the authors of this...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
on the web. Its structure is similar to that of the dynamic HTML used on some web pages, or the HTML applications used on Windows. If you've had experience developing with dynamic HTML, you'll probably find it relatively easy to pick up the knowledge you'll need to develop Firefox extensions. The role of each technology Firefox is largely built using four technologies: XUL, CSS, JavaScript, and
XPCOM. Extensions are also built using these four technologies. Figure 1: role of each technology in Firefox In addition to these technologies, extension development will require you to learn about how to confer privileges to overcome security restrictions on code that you write, and how to embed your code into the Firefox UI. These issues are discussed in Chapter 5. The minimum knowledge require...
Appendix D: Loading Scripts - Archive of obsolete content
ad scripts into their own global contexts which run in their own threads. In order to ensure thread safety, these contexts are extremely limited, can't be passed JavaScript objects, and have no access to the DOM. All communication between these contexts and outer contexts is marshalled through JSON encoding and decoding. ChromeWorkers also have access to ctypes and a limited number of thread safe
XPCOM classes, but are otherwise limited to simple computation based on data passed via messages and XMLHttpRequests. Advantages Asynchronous: Workers execute asynchronously in their own threads, which means that they have limited risk of interfering with the main thread. They may safely perform synchronous XMLHttpRequests or other intensive computation which would normally need to be broken up int...
Connecting to Remote Content - Archive of obsolete content
Text); }; request.onerror = function(aEvent) { window.alert("Error Status: " + aEvent.target.status); }; request.open("GET", url, true); request.send(null); In this example we demonstrate how to make a XMLHttpRequest call in asynchronous mode. You can see that an instance of the XMLHttpRequest class is created and it holds all functionality for making a request. We create this instance using
XPCOM instead of the usual way (new XMLHttpRequest()) because this way works both in chrome and non-chrome code. Following initialization, onload and onerror handlers are registered to a callback function to handle the response returned from the remote server. In both cases aEvent.target is an nsIXMLHttpRequest. In the onload callback function, the responseText parameter contains the server response a...
Custom XUL Elements with XBL - Archive of obsolete content
ame="aEvent" /> <body><![CDATA[ this.parentNode.removeChild(this); ]]></body> </method> As you can see, it's very easy to define a method and the parameters it takes. You can also have a return value using the return keyword, just like on regular JS code. The method uses the parent node to remove the Person node. Simple enough. You can do almost anything from XBL code, including using
XPCOM components, JS Code Modules and available chrome scripts. The main setback is that you can't have script tags defined in a binding, so you depend on the scripts that have been included in the XUL files that use the binding. Also unlike scripts, you can include stylesheets using the stylesheet XBL element. DTD and properties files can be handled just like in regular XUL. There are two conflicti...
Introduction - Archive of obsolete content
illa, it tends to be used to identify all Mozilla-related development. You'll sometimes read terms like "XUL applications" and "XUL extensions", but rarely will they refer to projects that are exclusively built with XUL. It usually means that the projects were built using Mozilla technologies. Even this project, called XUL School, covers several other technologies such as JavaScript, CSS, XBL and
XPCOM. XULRunner XULRunner includes the Gecko rendering engine, the Necko networking library, and several other components that provide OS-independent file management, accessibility, and localization, among others. It is this very powerful platform that has allowed such a fast growth of the development community surrounding Mozilla and Firefox. XULRunner is available in binary form at the XULRunner ...
Mozilla Documentation Roadmap - Archive of obsolete content
there are a few problems with it. First of all, the in-site search is not reliable, so we recommend using a search engine like Google, with queries such as "MDC Javascript Code Modules" or "Javascript code modules site:developer.mozilla.org". Secondly, there are several important articles that are very lacking in information, like the Preferences System page. And finally, what we mentioned in our
XPCOM section: almost no documentation on
XPCOM components. The documentation on interfaces is very complete, but it isn't nearly as useful as the documentation that existed at XULPlanet and was later taken down. XULPlanet allowed you to navigate between interfaces and their related components, which makes locating components very easy. Hopefully this will be corrected in the future. In the meantime, y...
User Notifications and Alerts - Archive of obsolete content
tification to be immediately closed, so you should only use notification boxes for single-step processes. The Alerts Service This is a very good option when you want to alert users about events without requiring input from them. Alerts are displayed in an OS-specific way, so their look is native. You can associate an action to the user clicking on the alert. Another advantage is that you use an
XPCOM service to do this (nsIAlertsService), so you can easily trigger alerts from chrome and non-chrome code. On the other hand, alerts are displayed only temporarily Using the Alerts Service is similar to using notification boxes: let alertsService = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService); let title = this._bundle.getString("xulschoolhello.greeting.title"); let mess...
XUL School Tutorial - Archive of obsolete content
ipt Object Management Basic functionality Adding menus and submenus Adding Toolbars and Toolbar Buttons Adding events and commands Adding windows and dialogs Adding sidebars User notifications and alerts Intermediate functionality Intercepting page loads Connecting to Remote Content Handling preferences Local Storage Advanced topics The Box Model
XPCOM Objects Observer Notifications Custom XUL Elements with XBL Mozilla Documentation Roadmap Useful Mozilla Community Sites Appendices Appendix A: Add-on Performance Appendix B: Install and Uninstall Scripts Appendix C: Avoiding using eval in Add-ons Appendix D: Loading Scripts Appendix E: DOM Building and HTML Insertion Appendix F: Monitoring DOM changes The XUL S...
Performance best practices in extensions - Archive of obsolete content
r can dynamically start or stop matching. Avoid unqualified ":hover" like the plague. Avoid DOM mutation event listeners DOM mutation event listeners are extremely expensive and, once added to a document even briefly, significantly harm its performance. As mutation events are officially deprecated, and there are many alternatives, they should be avoided at all costs. Lazily load services The
XPCOMUtils JavaScript module provides two methods for lazily loading things: defineLazyGetter() defines a function on a specified object that acts as a getter which will be created the first time it's used. See examples. defineLazyServiceGetter() 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. Look through the...
Promises - Archive of obsolete content
}) .then(null, (e) => { self.reportError("Publication failed", e); }); File IO File IO in add-ons should be done via the OS.File API, which provides a simple, but powerful, interface for reading, writing, and manipulating both text and binary files. It is also available for use off-main-thread in Workers as a synchronous API. This interface replaces the previous, complicated
XPCOM nsIFile and streams APIs, and their related JavaScript helper modules. These older interfaces should be avoided, even in their asynchronous forms, due to their performance penalties and needless complexity. Representative Example Usage Components.utils.import("resource://gre/modules/osfile.jsm"); Task.spawn(function* () { // Retrieve file metadata to check modification time. let info =...
Using the Stylesheet Service - Archive of obsolete content
aving to touch userContent.css or userChrome.css files. The API is defined in nsIStyleSheetService.idl. The stylesheets registered with this API apply to all documents; Firefox 18 extended nsIDOMWindowUtils with loadAdditionalStyleSheet() and removeAdditionalStyleSheet() to manage stylesheets for a specific document (bug 737003). The examples in this document are all written in JavaScript using
XPCOM. Using the API The string "chrome://myext/content/myext.css" in the examples below is just an example. Replace it with the URL of the CSS file you want to load. You can replace USER_SHEET with AGENT_SHEET or AUTHOR_SHEET, depending where in the CSS Cascade you want the sheet to be placed. See the CSS Specification for more details. Note that UA stylesheets are allowed to do certain unsafe thi...
Add-ons - Archive of obsolete content
ific locales, which have been translated to French since non-latin characters are not well supported). Hotfix Extension This document has been moved to the Add-ons wiki. How to convert an overlay extension to restartless First off, what kind of add-on are we talking about here? Well, XUL overlays and windows, JSM files, chrome & resource mappings with localization, default preferences, but no
XPCOM components of your own. Some of that will have to be replaced and the rest will need to be loaded differently. Inline options Firefox 7 supports a new syntax for defining extensions' preferences for both bootstrapped and traditional extensions. The user interface for the preferences defined with this new syntax appears in the extension's detail view in the Add-on Manager. This functionality ori...
BlackConnect - Archive of obsolete content
BlackConnect was a Blackwood subproject, trying to build a Java-to-
XPCOM bridge to allow interoperability between Java and
XPCOM components. The goal was to be able to implement
XPCOM components written in Java instead of C++. BlackConnect is now superseeded by Java
XPCOM. For the remainders of the BlackConnect project, see here. ...
Blackwood - Archive of obsolete content
gineers at Sun Microsystems, is an attempt to better integrate the Java platform with the Mozilla browser. Blackwood consists of a series of Java-based extensions to Mozilla. Blackwood's mission is to put Java support in Mozilla on a par with JavaScript support. Active Subprojects Webclient Java DOM API Java Pluglet API Defunct Subprojects BlackConnect -- Blackconnect was superseeded by Java
XPCOM ...
Building TransforMiiX standalone - Archive of obsolete content
This document is out of date. We support building a standalone version of TransforMiiX on Windows, Unix and OS X. Read the build instructions for your platform to get the requirements, which are the same as for Mozilla. You need to get the source from CVS. Add TX_EXE=1 mk_add_options BUILD_MODULES="
xpcom transformiix" ac_add_options --enable-standalone-modules="
xpcom transformiix" to your .mozconfig, and use client.mk to pull as usual. This will pull the necessary subtree with mozilla/client.mk mozilla/build/unix/modules.mk mozilla/build mozilla/config mozilla/expat mozilla/extensions/transformiix mozilla/include mozilla/allmakefiles.sh mozilla/client.mk mozilla/aclocal.m4 mozilla/configure mozilla/configure.in mozilla/Makefile.in plus nspr and
xpcom from the cvs repository. Building f...
Developing New Mozilla Features - Archive of obsolete content
Warning: The content of this article may be out of date. It was last updated in 2004. Tips For Contributing New Features To Mozilla. Learn the codebase and coding practices before you start your feature Include learning time in your schedule. Mozilla is a complex codebase. Our portability requirements may be new to even seasoned developers. Our cross-platform component model ("
XPCOM") is similar to COM, but you'll want to make sure you use it well before going too far with your project. And of course, we have a set of coding practices to help everyone live together. Life will be much easier if your team has one or more members who are already familiar with and to the Mozilla world. Develop relationships with existing developers in the area of your feature If you want to add a...
Drag and Drop - Archive of obsolete content
for an element when something is dropped on the element. At this point, the user has already released the mouse button. The element can simply ignore the event or can handle it some way, such as pasting the dragged object into itself. ondragend Called when the drag operation is finished. There are two ways that drag and drop events can be handled. This first involves using the drag and drop
XPCOM interfaces directly. The second is to use a JavaScript wrapper object that handles some of this for you. The code for this wrapper can be found in a file named toolkit/content/nsDragAndDrop.js nsDragAndDrop.js which is contained in the widget-toolkit (or global) package.
XPCOM Drag and Drop interfaces Two interfaces are used to support drag and drop. The first is a drag service, nsIDragService ...
Documentation for BiDi Mozilla - Archive of obsolete content
text mode of form controls may be "Logical", "Visual" or "Like Containing Document". We have also tested behaviour of all controls with dir=rtl and added support where necessary. Some support added for alignment in tables and lists, and fixes for problems with different combinations of dir and align. ...
Modularization techniques - Archive of obsolete content
to make every effort to make our interfaces compatible with COM on platforms that support it, so it may not matter. But no promises, yet. What are the major differences? Instead of Microsoft's MIDL compiler, we are using a CORBA-compliant IDL compiler, XPIDL. It outputs NSPR types when generating C++ headers. It also generates typelibraries that are not compatible with Microsoft's .TLB format.
XPCOM uses these typelibraries to allow other languages, such as JavaScript, to implement and call
XPCOM objects. We also do cross-thread proxying calls using the typelib and NSPR's event queues. Microsoft provides an extensive support infrastructure for COM. This technology is built into Windows, but not most other platforms. The technology can be licensed from Microsoft, but for obvious reasons we a...
Mozilla Application Framework - Archive of obsolete content
ick and painless. Gecko A performant web content rendering/editing engine with world-leading support for standards that you can drop into your application with a single line of XUL. Necko A wicked-fast, extensible networking library with built-in support for many common protocols and a well-defined plug-in interface for custom protocol handling so you can add the protocols you need.
XPCOM A simple, cross-platform component model with multiple language bindings and IDL descriptions so you can plug your custom functionality into the framework and connect it with other components. Web Services Built-in support for XMLHttpRequest, XML-RPC, SOAP, and WSDL to enable Mozilla-based application authors to take advantage of the exploding world of web services. XPInstall Our cross...
Build - Archive of obsolete content
prism Create a file called .mozconfig make sure it is in the mozilla/ directory. The contents of the file should look something like this : mk_add_options MOZ_CO_PROJECT=xulrunner mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/mozilla-obj ac_add_options --enable-application=xulrunner ac_add_options --disable-debug ac_add_options --enable-optimize ac_add_options --disable-tests ac_add_options --disable-java
xpcom Build xulrunner : make -f client.mk build Once the build is done, there will be a directory called mozilla-obj. Go into the prism/ directory and create a .mozconfig file mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/mozilla-obj/prism ac_add_options --with-libxul-sdk=../dist ac_add_options --enable-application=prism You need to define an environment variable to point the build to the new .mozconfig. T...
Scripting - Archive of obsolete content
ction. Methods of the window.platform object can be called from webapp.js or from web content. The following code can be used by web content to determine whether it is running in Prism: if ("platform" in window) { // Prism-specific code goes here } See the nsIPlatformGlue IDL definition file for details of the methods available to Prism apps. Currently, the webapp script also has access to full
XPCOM functionality, just like a Firefox extension. This level of functionality is commonly called chrome-level privileges. It means that the script has a higher level of privilege than scripts in the web content and has access to the file system, clipboard and other parts of the native OS. Note: In the future, the webapp script may have lower privileges. We are looking into the security aspects of the...
New Skin Notes - Archive of obsolete content
right now. --dria Yeah, I think we want them off by default, as the more common case for a reader will be to read documentation, not to edit it. --beltzner Put these back in. Will try to sort out how to change the default behaviour. --dria Headers which are also links that point to as-yet-unwritten wiki pages are colored as though they actually do exist. For an example of this, see Creating
XPCOM Components. --Waldo 21:09, 25 Aug 2005 (PDT) Not Going to Change (Yet or possibly Ever) Adding pipes between buttons in horizontal nav-bar (ie: My talk | Preferences | My watchlist) (stricken part is done). Also, and this is a nit, it's a little "my" crazy up there -- do we need all the "My"s? --beltzner Any chance we can mobe the "main page" scrollbar to the actual "content area" of the pa...
Static Analysis for Windows Code under Linux - Archive of obsolete content
tests ac_add_options --disable-embedding-tests ac_add_options --disable-installer ac_add_options --disable-accessibility ac_add_options --disable-vista-sdk-requirements ac_add_options --disable-updater #change this to where your libIDL-config file locate. HOST_LIBIDL_CONFIG=/usr/bin/libIDL-config #Config your moztools position GLIB_PREFIX=$HOME/moztools LIBIDL_PREFIX=$HOME/moztools #disable
xpcom stdcall calling convention because of gcc 4.3.0 bug CPPFLAGS="-DMOZ_DISABLE_
XPCOM_STDCALL" #Specify the CXX and static analysis #Point CXX to the cross compile g++ with plugin support CXX=$HOME/mingw-install/bin/i686-mingw32-g++ ac_add_options --with-static-checking=$HOME/dehydra/dehydra-gcc/gcc_dehydra.so Then, you can start building your Mozilla. The static check will be done when compiling i...
Table Layout Regression Tests - Archive of obsolete content
ld either all extensions or include layoutdebug in your .mozconfig file. For example ac_add_options --enable-extensions=all. a Mozilla tree with the test files at %MOZ_SRC%/layout/html/tests, DISABLE_TESTS should not be defined (so ac_add_options --enable-tests), patience and time. Test Runs Go to the %MOZ_SRC%/layout/html/tests/block directory. Avoid the nasty assertions to pop up by set
XPCOM_DEBUG_BREAK=warn, the world would be a much better place if we could first fix those assertions. As you will probably run your normal Mozilla in parallel with the testing issue then: set MOZ_NO_REMOTE=1 at the command prompt. Start the layout debugger via mozilla -layoutdebug - P foo where foo is just another profile than your main profile. Select from the Regression-Test Menu the Add New List...
URIs and URLs - Archive of obsolete content
only the mechanism responsible for generating or interpreting that component can determine whether or not escaping a character will change its semantics. Likewise, a URI must be separated into its components before the escaped characters within those components can be safely decoded. This implies that the segments of urls are escaped differently. This is done by NS_EscapeURL which is now part of
xpcom, but started as part of Necko. The information how to escape each segment is stored in a matrix. Also a string should not be escaped more than once. Necko will not escape an already escaped character unless forced by a special mask that can be used if it is known that a string is not escaped. Parsing URLs RFC 2396 defines an URL parser that can deal with the syntax that is common to most URL sche...
Venkman - Archive of obsolete content
ts with a useful set of debugger functionality implemented in C. Bandhauer then went on to reflect that API into Java, and create his cross platform front end, eventually producing Netscape JavaScript Debugger 1.0 and 1.1. In April of 2001, Robert Ginda began work on a JavaScript debugger for Mozilla, called Venkman. Venkman builds on the js/jsd portion of John's 1998 work, exposing it as an
XPCOM component. This allows the user interface be written in JavaScript and XUL, which allows Venkman to be fully cross-platform. Venkman is named after the character Dr. Peter Venkman, played by Bill Murray in the movies Ghostbusters and Ghostbusters II. Getting Venkman Firefox and Thunderbird The latest version of JavaScript Debugger is available from Fir...
When To Use ifdefs - Archive of obsolete content
le of platform-specfic ifdefs, see nsCRT.h. Feature ifdefs The mozilla code has many features that can be enabled or disabled by configure flags. For instance, it is possible to disable most of the XUL rendering engine by specifying --disable-xul when configuring the build. When adding ifdefs that implement these configure flags, care must be taken to obey the build dependencies. For instance,
XPCOM, the SpiderMonkey JavaScript engine, and the networking engine do not know anything about XUL and should not have any ifdefs based on --disable-xul. One special "feature ifdef" that deserves special attention is "MOZ_XUL_APP". This variable marks any application that is using the "toolkit". MOZ_XUL_APP ifdefs are not acceptable in tier 9, but are acceptable (even necessary) in later tiers. For an...
Install Wizards (aka: Stub Installers) - Archive of obsolete content
the three platform-specific versions of the stub installer follow the links below: Unix Stub Installer Mac Stub Installer Windows Stub Installer What do we mean by xpistub? The XPInstall engine is not called directly by the stub installer. The stub installer calls some glue code: xpistub which resides at: < http://lxr.mozilla.org/seamonkey/sou...pinstall/stub/> This "glue" code initialized
XPCOM and registers the XPInstall engine and requisite components to prepare for use by the stub installer. The stub installer hands off one-by-one a series of xpis to install. What do we mean by libxpnet? Cross-platform functionality for making file transfers across a network is provide by the library libxpnet. Complete details about this library is available at libxpnet: Architecture and API Overv...
Working With Directories - Archive of obsolete content
ptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative
XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. A reference to a directory may be created in the same way as with a file by using nsIScrip...
Getting File Information - Archive of obsolete content
ptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative
XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. The nsIFile object has a number of useful attributes which may be used to retrieve inform...
Reading from Files - Archive of obsolete content
ptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative
XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. Reading data from a file involves getting a reference to a file and then creating an input...
Uploading and Downloading Files - Archive of obsolete content
ptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative
XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. The IO object and stream objects can be used to upload files to servers in various ways. ...
Writing to Files - Archive of obsolete content
ptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative
XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. To write to a file, an output stream is used. An output stream is an object which can be ...
IO - Archive of obsolete content
ptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative
XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. Files and Streams This section describes how to access and get information about files, re...
Moving, Copying and Deleting Files - Archive of obsolete content
ptableIO | Accessing Files | Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative
XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. There are several methods of the nsIFile object which may be used to move and copy files ...
Node - Archive of obsolete content
Constants The nsIDOMNode interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. ...
appLocale - Archive of obsolete content
<< XUL Reference appLocale Obsolete since Gecko 1.9.1 Type: nsILocale Returns the
XPCOM object which holds information about the user's locale. This is an object which implements nsILocale. Gecko 1.9.1 note This property was removed in Gecko 1.9.1. ...
builder - Archive of obsolete content
For scripts it is only necessary in case you want to force the template content to be regenerated. You may need to do this if you have adjusted the rules manually. To rebuild the content call the builder's rebuild method. ...
Template and Tree Listeners - Archive of obsolete content
nsIXULTreeBuilderObserver - used to listen to particular tree operations. nsIRDFObserver - for RDF datasources, used to listen to changes in the underlying RDF datasource. Listening for Template Rebuilds The first of these is the simplest and involves two methods, willRebuild and didRebuild. ...
Install Scripts - Archive of obsolete content
e set of files and version information about the installed components. That way, it is easier to check if a version of your component is already present and only update it if necessary. The component registry works somewhat like the Windows registry does. It consists of a hierarchy of keys and values. You don't need to know much about it to create XUL applications unless you are creating your own
XPCOM components. What you do need to know for an installation is that the registry stores a set of information about your application, such as the file list and versions. All of this information is stored in a key (and within subkeys) that you provide in the installation script (in step 1 mentioned above). This key is structured as directory-like path of the following form: /Author/Package Name Repla...
XUL Tutorial - Archive of obsolete content
ntent Panels Splitters Toolbars and Menus Toolbars Simple Menu Bars More Menu Features Popup Menus Scrolling Menus Events and Scripts Adding Event Handlers More Event Handlers Keyboard Shortcuts Focus and Selection Commands Updating Commands Broadcasters and Observers Document Object Model Document Object Model Modifying a XUL Interface Manipulating Lists Box Objects
XPCOM Interfaces
XPCOM Examples Trees Trees More Tree Features Tree Selection Custom Tree Views Tree View Details Tree Box Objects RDF and Templates Introduction to RDF Templates Trees and Templates RDF Datasources Advanced Rules Persistent Data Skins and Locales Adding Style Sheets Styling a Tree Modifying the Default Skin Creating a Skin Skinning XUL files by hand Local...
The Implementation of the Application Object Model - Archive of obsolete content
s much smaller and easier to plug into than the 4-5 interfaces required if directly implementing the content tree interfaces. Furthermore, should the content tree interfaces change, only this layer would need to be updated. The pluggable content, safe behind this layer, wouldn't have to change at all. One natural solution to try for implementing such a layer might be inheritance. However, in this
XPCOM world, where each type of pluggable content is off in its own DLL, there's no clean way to inherit functionality from some base class implementation, when that implementation must necessarily reside in a different DLL, without introducing a code dependency between all pluggable content and the common base class. This inability to provide a cleanly inherited system argues for a different approach,...
XML - Archive of obsolete content
ifferent standards: CSS for styling or "skinning", DOM for the object model and scriptable access, JavaScript for the linking and behavior, RDF for resources, XML for the structure, and HTML for the content and some little extras. In this way, it's more like a developmentplatform or framework than a user interface language, particularly when it's used with related cross-platform technologies like
XPCOM, which also went into Mozilla. Gecko Reads XUL and Makes Interfaces Just as our specially created memo is nothing but text unless there is an application for making use of the structure in some way, so too our XUL widgets are just marked-up text unless there is software to interpret the structures and render the XUL as actual widgets. All XML requires a parser or an engine of some kind at the r...
scrollbox - Archive of obsolete content
u want to programmatically scroll in addition to the automatic scroll bars. Note: avoid nested scroll boxes; it's maddening for the experienced user and confusing for the less experienced user. Instead, figure out some other way to lay things out. Scrolling a child element into view See element.scrollIntoView. Prior to Gecko 19, scrollIntoView() didn't exist in XUL. Do this instead: var
xpcomInterface =scrollbox_element.boxObject.QueryInterface( Components.interfaces.nsIScrollBoxObject);
xpcomInterface.ensureElementIsVisible(child_element_to_make_visible); See the nsIScrollBoxObject API for other scroll-related methods. Attributes Inherited from XUL element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment,...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
able to be expanded). You will also need to include a branding/ subdirectory. Follow the example in McCoy carefully since XULRunner is sensitive about having exactly the right files in exactly the right packages. The components/ subdirectory If you are reading this guide, you probably need to include C++ components in your application. If you've never done this before, you should consult Creating
XPCOM Components or another
XPCOM reference. The public/ and src/ directories that you put in the components/ directory will look the same as for an extension that includes C++ components, so you can use the relevant sections of Creating Custom Firefox Extensions with the Mozilla Build System as a reference. The makefiles, however, will be difference since you won't be defining things like XPI_NAME (th...
Deploying XULRunner - Archive of obsolete content
Library/Frameworks/XUL.framework/Versions/1.8/xulrunner.) libmozglue.dylib (the main XUL library) ... other executables and libraries The core changes to XUL and Gecko that require this new file layout were implemented in Gecko 34, except that the XULRunner application was not updated to know about the change, so it will report an error: "Unable to load
XPCOM." XULRunner was fixed in Gecko 39. See this blog post for additional background about this change. XULRunner 38 and earlier In XULRunner 38 and earlier, XULRunner is provided in a Mac OS X Framework bundle, which is placed in your application bundle's Frameworks directory. The complete bundle structure is as follows: MyApp.app/ Contents/ Info.plist PkgInfo Framew...
How to enable locale switching in a XULRunner application - Archive of obsolete content
localeswitchdemo content/ locale localeswitchdemo de-DE locale/de-DE/ locale localeswitchdemo en-GB locale/en-GB/ locale localeswitchdemo fr-FR locale/fr-FR/ How are you going to populate the XUL listbox? You can hardwire the choices into the XUL code using fixed list items, or could take the elegant approach and construct the list dynamically. The dynamic list population requires an
XPCOM to query the currently selected locale as well as all locales available in the application package. Here is a code snippet showing how this is done: The definition of the XUL control: <listbox id="locale-listbox"> <!-- generated list items go in here --> </listbox> <button label="&switchLocale.button;" oncommand="changeLocale()"/> The Javascript code to populate the control: try { // Query a...
XULRunner - Archive of obsolete content
It provides mechanisms for installing, upgrading, and uninstalling these applications. XULRunner also provides libxul, a solution which allows the embedding of Mozilla technologies in other projects and products. Releases Until version 41, XULRunner could be downloaded from ftp.mozilla.org. ...
XUL Explorer - Archive of obsolete content
Installs Latest Version: Install (Windows): xulexplorer-1.0a1pre.en-US.win32.exe 6.6MB Install (Mac): xulexplorer-1.0a1pre.en-US.mac.dmg 9.3MB Install (Linux): xulexplorer-1.0a1pre.en-US.linux-i686.tar.bz2 8.4MB Contributing Source code in SVN Bugzilla (for bu...
mozilla.dev.platform FAQ - Archive of obsolete content
ll-app Q: Can you build XULRunner with newer (>1.5) features, such as storage? A: XULRunner trunk and 1.8 (but not 1.8.0) build storage by default, and anything can be built with storage if you put in you <tt>mozconfig --enable-storage</tt> Q: Program received signal EXC_BAD_INSTRUCTION, Illegal instruction/operand. 0x00016b50 in XRE_CreateAppData () A: When you <tt>--disable-libxul</tt>, the
XPCOM glue doesn't have information about how to load all the dependent libraries like <tt>libgfx.dylib</tt>. In order to use XR successfully in <tt>--disable-libxul</tt> mode, you have to setup DYLD_LIBRARY_PATH to include <tt>/Library/Frameworks/XUL.framework/Versions/1.9a1</tt> - Benjamin Smedberg, Fri, Oct 20 2006 9:12 am Q: When I try to build a completely standalone XUL app on OS X (10.4.8). to...
nsIContentPolicy - Archive of obsolete content
in with nsICategoryManager. See example below. char* previous = nsnull; nsCOMPtr<nsICategoryManager> catman; servman->GetServiceByContractID(NS_CATEGORYMANAGER_CONTRACTID, NS_GET_IID(nsICategoryManager), getter_AddRefs(catman)); rv = catman->AddCategoryEntry("content-policy", COMPONENT_CLASSNAME, COMPONENT_CONTRACTID, PR_TRUE, PR_TRUE, &previous); JavaScript developers can also implement an
XPCOM component that extends nsIContentPolicy. ...
2006-10-20 - Archive of obsolete content
A commonly asked question in many newsgroups. Jesper Kristensen pointed the requester here Change download action for .rdp files on Windows and OS X A question regarding enabling Firefox to associate .rdp files with Microsoft Remote Desktop Client so that the correct application opens the files automatically. Method ShouldLoad in "content-policy" Category Problem ? A student learning
XPCOM is having issues with the method ShouldLoad in the interface nslContentPolicy. When the method is executed Firefox crashes. As of yet there are no responses. IE7 RSS Reader Better - Say Reviewers A discussion revolving around the quality of RSS readers in IE7, Firefox and other assorted browsers. Also a debate about which browser is "beating" which to a lesser extent further in the discussio...
2006-10-06 - Archive of obsolete content
Summary: mozilla.dev.builds - September 30th to October 6th 2006 TB MOZILLA_1_8_BRANCH build problem on Mac OS X (10.4.7, universal build) Ludwig Hugelschafer stated that he has been encountering an error when he executes a "make export" operation on ThunderBird (part of the MOZILLA_1_8_BRANCH) since September 15th. ../../dist/host/bin/host_xpidl -m header -w -I~mozilla/
xpcom/base -I../../dist/idl -o _xpidlgen/nsIConsoleListener ~/mozilla/
xpcom/base/nsIConsoleListener.idl gmake[2]: *** [_xpidlgen/nsIConsoleListener.h] Bus error gmake[2]: *** Deleting file `_xpidlgen/nsIConsoleListener.h' gmake[1]: *** [export] Error 2 make: *** [all] Error 2:: On Octorber 4th Ludwig Hugelschafer responded to his original post with the solution to his own problem. He found out that a...
2006-11-24 - Archive of obsolete content
to build Xulrunner using the ming compiler on WindowsXP. However he has been unsuccessful and a bunch of errors. To view the Joe's error please check the posting. He is using make 3.80, working with the source tarball for xulrunner 1.8.4,running "make -f client.mk distclean" followed by "make -f client.mk build_all". Joe is asking for help on a possible solution to fix his problem. Building
XPCOM components with MSVS 2005 November 21st: Buffaloaf is having trouble getting a personal
XPCOM component to work under XulRunner when compiled with MSVS 2005. Luke is migrating all of his code to compile with vc8 and is having some problems. He is receiving the following error: Error: uncaught exception: [Exception... "Component returned failure code: 0x80570016 (NS_ERROR_XPC_GS_RETURNED_FAIL...
2006-10-27 - Archive of obsolete content
Summary: mozilla.dev.platform - October 21st to October 27th 2006 Announcements No announcments this week. Traffic Status of
XPCOM cycle collector Graydon Hoare provides the
XPCOM patch which experiments with implementing a general-purpose garbage-cycle collector for
XPCOM. Meetings No meetings this week ...
2006-11-17 - Archive of obsolete content
:Reflow...ng#Quick_Links. Users are asked to file bugs on encountered problems that are not present on the current trunk builds. If bugs are filed, "[reflow branch]" should be placed at the beginning of the summary. Parsing HTML into a document object in Fx3 Discussion if Gecko 1.9 will support parsing HTML into a document object. The possibility of turning the MicrosummaryResource object into a
XPCOM component, which accomplishes this task in a "hacky" manner, was also discussed. Meetings None this week. ...
2006-09-22 - Archive of obsolete content
Discussions Java vs.
XPCOM discussion of the limitation and merits of Java in place of
XPCOM. xpidl.exe crashes on Windows problem with creating header files from IDL's in 1.8 branch due to wrong compiler. ...
2006-09-30 - Archive of obsolete content
Summary: mozilla.dev.tech.
xpcom - Sept 30- Oct 5, 2006 Announcements Build a
xpcom component on Mac OS X Benjamin Smedberg confirmed that this tutorial http://www.iosart.com/firefox/
xpcom/ is misleading as it uses the standalone glue (-D
XPCOM_GLUE) for components, which is not recommended. Developers should use this sample instead: http://developer.mozilla.org/en/docs/
XPCOM_Glue Discussions Dynamic load overlay A short discussion about the possibilities of loading and unloading xul overlay runtime Reading binary data from file Discusses about the code to read binary data from file How to build
xpcom component on Mac OS X Discusses about the Make file code used to build
xpcom components on Mac OS X successfully Meetings None during this week. ...
2006-10-13 - Archive of obsolete content
Summary: mozilla.dev.tech.
xpcom - Oct 13-20, 2006 Announcements None during this week. Discussions wxMozilla and FF1.5
XPCOM problems updating wxMozilla to use it with Firefox 1.5.7 Browser elements, Opening links in a new window Using javascript to open window in new window. General
XPCOM and nsCOMPtr questions nsCOMPtr basics regarding myIComponent usage. Fedora security blocking
XPCOM registration Fedora Core 5.0 security settings impeding
xpcom registration. Meetings None during this week. ...
2006-10-27 - Archive of obsolete content
Discussions evalInSandbox and XMLHttpRequest A discussion about writing something that calls a function defined by the page that the user is currently on Chrome files and last modified date Ways to retrieve the last modified date of a chrome file that may be in a jar or on the file system. ...
2006-11-10 - Archive of obsolete content
Discussions Developing an extension like XmlHttpRequest / nsIDocument / MOZILLA_INTERNAL_API A discussion on how to develop an extension similar to XmlHttpRequest but for a different protocol than Http, emulating the asynchronous aspect. ...
2006-11-17 - Archive of obsolete content
Summary: mozilla.dev.tech.
xpcom - Nov 11-Nov 17, 2006 Announcements None during this week. Discussions XPIDL crashes IMyComp.h problems: "xpidl.exe has encountered a problem and needs to close" Meetings None during this week. ...
2006-11-24 - Archive of obsolete content
Summary: mozilla.dev.tech.
xpcom - Nov 18-Nov 24, 2006 Announcements None during this week. Discussions Tutorials: non C++ bindings for
XPCOM Tutorials on how to interface with Firefox using
XPCOM on a similar basis to how a developer can with Internet Explorer through it's COM interface Tutorals and References related to extension development Tutorials on developing extensions which use the third party libraries for firefox References to mozilla API Exposed JavaScript Component + XMLDocument not accessible A discussion on Error: uncaught exception: Permission denied to get property XMLDocument.textContent Creating
XPCOM components A good discussion about "Components.classes[cid] has no properties" error Firefox HTTP Explanation about how Firefox handles the HTTP a...
2006-12-01 - Archive of obsolete content
Discussions nsIContentPolicy and user interaction The proper way to get user confirmation before trying to load certain file types. debugging firefox extesnion? A tip on how to debug Firefox extensions using a debugger. segmentation fault while running the browser Browser crashes after installation of subjects extension. ...
2006-12-08 - Archive of obsolete content
Discussions
XPCOM cpp to js callback Engaging discussion on a problem with trying to call back from C++ to a JavaScript object using an interface the developer created with an idl. However, the C++ call that's supposed to be invoking the method on the JavaScript object is returning with 0x80004005 (NS_ERROR_FAILURE). ...
2006-11-17 - Archive of obsolete content
Summary: mozilla.dev.apps.calendar - November 10 - November 17, 2006 Announcements No meeting for this week. Discussions iTIP and iMIP new designs for sending invitations available for comment Discussion about the new interface designs for iTIP. view performance Discussion about tests on view performance. webdav server A discussion related to remote calendar modifications. Calendar
XPCOM Component Discussion about a debug error of AddItem function from calICalendar. Meetings No Meetings were scheduled this week. Authors Mark Paruzel Yi (Eric) Shen [Back to Weekly Summaries ] ...
Newsgroup summaries - Archive of obsolete content
006-10-06mozilla.dev.apps.calendarmozilla.dev.tech.js-enginemozilla-dev-accessibilitymozilla-dev-apps-calendarmozilla-dev-apps-firefoxmozilla-dev-apps-thunderbirdmozilla-dev-buildsmozilla-dev-embeddingmozilla-dev-extensionsmozilla-dev-i18nmozilla-dev-l10nmozilla-dev-planningmozilla-dev-platformmozilla-dev-qualitymozilla-dev-securitymozilla-dev-tech-js-enginemozilla-dev-tech-layoutmozilla-dev-tech-
xpcommozilla-dev-tech-xul ...
New in JavaScript 1.8 - Archive of obsolete content
a tracking development bug for JavaScript 1.8. Using JavaScript 1.8 In order to use some of the new features of JavaScript 1.8 in HTML, use: <script type="application/javascript;version=1.8"> ... your code ... </script> Another way (not recommended) to do this is to use the deprecated <script> language attribute and define it as "JavaScript1.8". When using the JavaScript shell, JavaScript
XPCOM components, or XUL <script> elements, the latest JS version (JS1.8 in Mozilla 1.9) is used automatically (bug 381031, bug 385159). The features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 or higher because existing code might use those keywords as variable or function names. The features that do not introduce new keywords (such as generator expre...
RFE to the XForms API - Archive of obsolete content
e to be queried from the XForms element that resides in the DOM. For example, every visual XForms element exposes the nsIXFormsDelegate interface. If you need some additional functionality that shouldn't be exposed from the XForms element directly, then you should think which interface of the XForms element is more appropriate to expose it. Mozilla XForms doens't offer any service you can get via
XPCOM. As an example, the nsIXFormsAccessors interface which allows a user to get/set the value of an instance node and get the state of an instance node, is exposed by the nsIXFormsDelegate interface using the accessors property. XForms DOM Put here your requirements how to improve XForms DOM API. Reflect attributes to properties For the elements that can contain the incremental or selection att...
XQuery - Archive of obsolete content
wishing to access XQuery in their own extensions At present, the extension works simply by using LiveConnect to work with Berkeley DB XML's Java API (and via a Java wrapper class which circumvents LiveConnect's current inability to handle some types of Java exceptions properly). However, use of the approach of the Java Firefox extension might be used to turn the above extension concept into an
XPCOM component (giving it access to all open windows), and for Berkeley DB XML, possibly implementing it in C++ instead, which is that database's original language of development. However, the extension demonstrates a technique which does not depend on using
XPCOM, while still giving full privileges. Tutorials W3Schools Learn XQuery in 10 minutes An introduction to XQuery ...
XUL Parser in Python - Archive of obsolete content
stration of using Python's XML parser with XUL. But Mozilla's upcoming support for languages like Perl and Python will really open up the Mozilla platform to tools and approaches of this kind--and make now a good time to start thinking about how these various technologies will be put together. The first level of support for Python in Mozilla will apparently be for Python modules made available as
XPCOM objects. Extending on the approach in this script, then, you could imagine a kind of introspective XUL chrome that could modify and replicate itself by calling services from the XULParser and XULWriter
XPCOM objects. Please feel free to suggest changes, change the format of the results output, or adapt this script in any way you want. I have probably made some errors and undoubtedly written so...
omni.ja (formerly omni.jar)
a contents The omni.ja file contains assorted application resources: chrome.manifest The chrome manifest file. /chrome/ User interface files for the application /chrome/localized.manifest Manifest of localized content; referenced by the main chrome manifest file. /chrome/nonlocalized.manifest Manifest of non-localized content; referenced by the main chrome manifest file. /components/
XPCOM components the application relies upon. /defaults/ Default preference files. /modules JavaScript code modules. /res/ Miscellaneous resource files. ...
Multiprocess on Windows
apartment, readers of this document should have a solid understanding of what apartments are. Unfortunately this topic is often poorly explained. One of the better pieces of documentation is a two-part series written by Jeff Prosise: Understanding COM Apartments, Part I Understanding COM Apartments, Part II For the purposes of this document, "COM" will refer to Microsoft COM (as opposed to
XPCOM). Gecko and apartments Most code that runs on Gecko's main thread is not thread safe. Since Gecko's main thread uses COM, and COM requires threads to declare their threading model, the main thread must initialize itself to live inside its own single threaded apartment (STA). This is true for both chrome and content processes. As you should already know from the prerequisite reading, single thr...
Adding a new event
3 (non-DOM events), you can skip this section. Create WebIDL of the event Write a DOM event definition with WebIDL. It should be created under dom/webidl/. See WebIDL bindings for the detail. If your new event shouldn't be created with event constructor such as: var event = new FooEvent("bar", { bubbles: true, cancelable: true, detail: 5 }); you shouldn't define construnctor in it. Create
XPCOM interface for the DOM event If your event class should be accessible via
XPCOM interface, you should create a new nsIDOMFooEvent interface in dom/interfaces/events/. However, in these days, this is not necessary. If all information of the event is stored by its internal event, C++ event handlers can access them with following code: NS_IMETHODIMP AnEventListener::HandleEvent(nsIDOMEvent* aEvent)...
Creating JavaScript callbacks in components
These interfaces are used to manipulate the component in C++ and JavaScript. A common pattern used with interfaces to create a bi-directional communication between two groups of code is the observer (or listener) pattern. Basically, the component defines an observer (or listener) interface which is implemented by some external code and this implementation is passed to the component. The component can then call methods on the observer interface to signal the external code when predefined events occur. ...
Working with Mozilla source code
his isn't a good way to download the code, but is a great way to search it. Navigating the Mozilla source code Learn about the various folders in the Mozilla source tree, and how to find what you're looking for. Bugs for newcomers If you are new to the project and want something to work on, look here. Interface development guide Guidelines and documentation for how to create and update
XPCOM interfaces. The Firefox codebase: CSS Guidelines This document contains guidelines defining how CSS inside the Firefox codebase should be written, it is notably relevant for Firefox front-end engineers. SVG Cleanup Guide Guidelines and best practices for shipping new SVGs. Try Servers Mozilla products build on at least three platforms. If you don't have access to them all, you can use the t...
Frame script environment
tab global. This means you don't have to worry about global variables you define conflicting with global variables defined by another frame script. You can still access the global directly via this. Frame scripts run with system principals. If you want other principals, you can use a Sandbox. Frame scripts run with system privileges and have access to the Components object, enabling them to use
XPCOM objects and JSMs. However, some APIs that work in the chrome process will not work in a frame script. See Limitations of frame scripts for more details. Events Besides the regular DOM events being captured/bubbling up from content the current content object the following additional events get fired in a frame script environment: unload Fires when the frame script environment ...
Limitations of frame scripts
Many privileged APIs will just work in a content process. Anything that just manipulates data structures will just work. XHR and Workers will work. However, some APIs that work in the chrome process will not work in a frame script. This article lists the most important of these APIs. This is one of a pair of articles: the other one lists limitations of chrome scripts. Security Restrictions on File Access Processes that host remote content are isolated from the local system through a content security sandbox. ...
Communicating with frame scripts
output somewhat like this, when the user clicks a <div>: "my-addon@me.org:my-e10s-extension-message" false Object { details: "they clicked", tag: "div" } <xul:browser anonid="initialBrowser" ... > { target: <div#searchContainer> } If your code requires access to a window (for example to run window.openDialog), and your message listener is run from somewhere without access to a window (e.g. an
XPCOM component), you can access the window of the browser that sent the message with message.target.ownerDocument.defaultView. Synchronous messaging To send a synchronous message, the frame script uses the global sendSyncMessage() function: // frame script sendSyncMessage("my-addon@me.org:my-e10s-extension-message"); When a chrome script receives a synchronous message, it should return a value fro...
Frame script environment
global variables you define conflicting with global variables defined by another frame script. You can still access the global directly using this. Frame scripts run with system principals. If you want other principals or when interacting with untrusted page scripts, you should use a Sandbox. Frame scripts run with system privileges and have access to the Components object, enabling them to use
XPCOM objects and JSMs. However, some APIs that work in the chrome process do not work in a frame script. See Limitations of frame scripts for more details. Events Besides the regular DOM events being captured/bubbling up from content the current content object the following additional events get fired in a frame script environment: unload Bubbles No Fires when ...
Limitations of frame scripts
Many privileged APIs will just work in a content process. Anything that just manipulates data structures will just work. XHR and Workers will work. However, some APIs that work in the chrome process will not work in a frame script. This article lists the most important of these APIs. File I/O You should not write to or read from the disk from a frame script, in particular, the profile directory. Even if this is possible, you should not do it and may expect that it could stop working at any time. File I/O should all be done in the chrome process. ...
Performance
ovide some middle ground for some addons. It does not provide the same memory footprint reductions but it improves application startup. Beam down information in advance to avoid synchronous calls to the parent BAD: // processscript.js function ContentPolicy() { // ... ...
Embedding Tips
Normally it provide some functionality that is required from lots of places such as looking up preference settings, creating new windows, locating files, displaying prompt or password dialog boxes and so on. Embedders may wish to override some of the default service implementations with their own. For example, the default prompt service uses XUL to render prompt dialogs and embedders may wish to render them in a way more appropriate for their application and platform.. ...
Embedding Mozilla
n, some possible embedding scenarios that we need to deal with, and an embedding solution that will fulfil them. Roll your own browser - An embedding HowTo A quick introduction to embedding Mozilla. View All... Community View Mozilla forums... Mailing list Newsgroup RSS feed #embedding IRC channel Related Topics Gecko,
XPCOM ...
How Mozilla determines MIME Types
the specified MIME type will be used. (i.e. the list in Edit/Preferences/Helper Applications) If that failed, a list of "extra" MIME types is searched for an extension match. See line 507 for the complete list. If that also failed, the list of loaded plugins is checked for a plugin that can handle this extension, and is asked for the MIME type If no plugin is registered, the ext-to-type-mapping
XPCOM category is searched for the extension. This allows extensions to register additional mappings. The key of the category entry is the extension without leading dot, the value is the MIME type. The extension must be lowercase. If no ext-to-type-mapping category is found, the ExternalHelperAppService returns application/x-extension-EXT, where EXT is the extension of the file. Helper Applications ...
IPDL Tutorial
d, and private labels in C++. Parameters Message declarations allow any number of parameters. Parameters specify data that are sent with the message. Their values are serialized by the sender and deserialized by the receiver. IPDL supports built-in and custom primitive types, as well as unions and arrays. The built-in simple types include the C++ integer types (bool, char, int, double) and
XPCOM string types (nsString, nsCString). IPDL imports these automatically because they are common, and because the base IPC library knows how to serialize and deserialize these types. See ipc/ipdl/ipdl/builtin.py for the most up-to-date list of automatically imported types. Actors may be passed as parameters. The C++ signature will accept a PProtocolParent* on one side and convert it to a PProtocolCh...
IPDL Type Serialization
late <> struct ParamTraits<MyType> { typedef MyType paramType; static void Write(Message* aMsg, const paramType& aParam) { // implement serialization here } static bool Read(const Message* aMsg, void** aIter, paramType* aResult) { // implement deserialization here. return false if deserialization failed } }; } // namespace IPC The standard IPDL types (integers, floats, and
XPCOM strings) already have serializers. Other types need to have serializers written for them explicitly. In many cases a serializer can be written by combining existing serializers. Most structures can be serialized in this manner: struct ExampleStruct { int i; nsCString j; int k[4]; }; namespace IPC { template <> struct ParamTraits<ExampleStruct> { typedef ExampleStruct paramType; sta...
Implementing QueryInterface
assignments to *aInstancePtr, which compilers have trouble optimizing. It clears the result, *aInstancePtr, when returning an error. It generates less code than the typical implementation of QueryInterface. It tests for bad input with an NS_ASSERTION, to find logic errors immediately in debug builds. Some Alternatives The NS_IMPL_QUERY_INTERFACE[012] macros The sample above implements two
XPCOM interfaces in addition to nsISupports. The NS_IMPL_QUERY_INTERFACE2 macro can write this function for you (though it pains me to recommend macros), e.g., NS_IMPL_QUERY_INTERFACE2(nsMyImplementation, nsIX, nsIY) // implements |nsMyImplementation::QueryInterface| as above NS_IMPL_QUERY_INTERFACE1(nsFoo, nsIFoo) // |nsFoo::QueryInterface| provides |nsI...
OSFile.jsm
What are the relationships with the HTML5 File API? None, really. ...
PromiseWorker.jsm
mmary A PromiseWorker is a ChromeWorker except instead of calling postMessage() to send a message, you call post(), which returns a Promise. JavaScript files imported into the worker scope and main thread scope which allows posting to the worker and receiving in the form of a promise. Like ChromeWorker objects, PromiseWorker is mostly used for js-ctypes but it is not limited to that. There is no
XPCOM access, similar to ChromeWorker. This answers the question "When should I use a PromiseWorker?", and the answer is, whenever you would normally use a ChromeWorker, but want postMessage to return promises. The PromiseWorker object is used to deliver all of the OS.File functionality to the main thread. Here is the test case from Firefox codebase: Mozilla DXR :: test_Promise.js. PromiseWorker modu...
Mozilla Development Strategies
hours or a day to fix. In theory, fixes for these bugs will be quick to review. If you have problems finding smaller, easier bugs to work on, start by looking for crashers. Maybe the problem can be turned into an assert, or fixed altogether. You can use talkback queries or Bugzilla queries to find crashers. Look for problems in existing code. Find and fix string usage problems. Find and fix bad
XPCOM macro usage. Switch some code over to nsCOMPtrs. Look for XXX or TODO in the code, verify the code still needs fixing, and fix it. Smaller patches get reviewed faster If you find that you spend a lot of time waiting for reviews, keep in mind that patch size is not linear to time to review. A twenty line patch doesn't take twice as long to review as a ten line patch, it usually takes much more t...
JS::PerfMeasurement
tions, etc. Each potentially-measurable event corresponds to a regular old instance variable, which you can read and even modify. All presently-measurable events are measured with counters, not timers; that is, there is no defined relation between the numbers you get from this interface, and wall-clock time. PerfMeasurement* JS::ExtractPerfMeasurement(jsval wrapper) If you are the C++ side of an
XPCOM interface, and you want to benchmark only part of your execution time but make the results available to JavaScript, you can declare a bare jsval argument in your .idl file and have JavaScript pass a PerfMeasurement object that it created in that argument slot. The jsval you receive points to a JavaScript wrapper object. To extract the C++-level PerfMeasurement object, call this function. It wi...
TraceMalloc
ons(filename); </script> One can then use the script tools/trace-malloc/diffbloatdump.pl to compare trace-malloc dumps before and after doing an action that might leak. If there are significant differences, it might be worth examining the call stacks for the destructors of the objects in question to see what is extending their lifetime. (This can be done by examining the unprocessed output of an
XPCOM_MEM_REFCNT_LOG, one of the nsTraceRefcnt logs.) You should use the --use-address argument to diffbloatdump.pl, and then the diff tree can be run through fix_linux_stack.py or fix_macosx_stack.py as needed. Leaksoup Leaksoup is a trace-malloc tool that analyzes the shutdown log. Because this log includes the contents of heap blocks, leaksoup can analyze the graph of live objects and determine whic...
Preferences
illa preferences for uber-geeks A guide to preferences that only truly elite geeks should play with. Examples Code snippets Preference-related code snippets. Adding preferences to an extension How to add preferences to an existing extension. Related Topics XUL, JavaScript,
XPCOM, Extensions, Developing Mozilla ...
Leak And Bloat Tests
im To provide a continuous check within MailNews and its sub-components for the following items: Total memory leaks. Total memory usage (aka bloat). Provide a consistent number from build to build where no source code has changed. Provide reasonable coverage for the normal activities that a user performs. Method Current Method: Measure Leaks and Bloats, in a similar way to Firefox (using
XPCOM_MEM_LEAK_LOG and --trace-malloc). The method of testing memory bloat and leaks will be the same sequence of events, using the same set of test data. Startup Main Mail Window Open Address Book and Message Composition windows Close Address Book and Message Composition windows Quit the application Future improvements will be discussed on the discussion page of the Mozilla wiki. Results Printed ...
Hash Tables
ypes and Constants Hash Table Functions Hash Table Types and Constants PLHashEntry PLHashTable PLHashNumber PLHashFunction PLHashComparator PLHashEnumerator PLHashAllocOps Hash Table Functions PL_NewHashTable PL_HashTableDestroy PL_HashTableAdd PL_HashTableRemove PL_HashTableLookup PL_HashTableEnumerateEntries PL_HashString PL_CompareStrings PL_CompareValues See also
XPCOM hashtable guide ...
PRUnichar
An unsigned 16-bit type, like char in Java or the "characters" of a JavaScript string defined in /mozilla/
xpcom/base/nscore.h. Syntax #if defined(NS_WIN32) typedef wchar_t PRUnichar; #else typedef PRUInt16 PRUnichar; #endif ...
Necko FAQ
wanted to know about the networking library in mozilla... and did ask. What is Necko? A word rhyming with Gecko and starting with the same letters as networking. That's all! Any resemblance in flavor to the Necco candy is purely coincidental. What do I need to build this library? See the code section on the main page. Currently you'd need to get the mozilla tree and at least build NSPR, and
XPCOM. TODO put links! How does PSM fit into this picture? Todo How does the proxy support work? Todo What about Proxy Auto Config? Todo What about SOCKS support? Todo When is the next stable release of this library going to be available? Todo I'd like to use this library for my project. What licences apply? Todo - MPL What do the page load options mean in the preferences? Todo ...
JSClass.flags
JSCLASS_HAS_PRIVATE This class uses private data. If this flag is set, each instance of the class has a field for private data. The field can be accessed using JS_GetPrivate and JS_SetPrivate. MXR ID Search for JSCLASS_HAS_PRIVATE JSCLASS_PRIVATE_IS_NSISUPPORTS Mozilla extension. The private field of each object of this class points to an
XPCOM object (see nsISupports). This is only meaningful if SpiderMonkey is built with XPConnect and the JSCLASS_HAS_PRIVATE flag is also set. MXR ID Search for JSCLASS_PRIVATE_IS_NSISUPPORTS JSCLASS_IS_DOMJSCLASS Added in SpiderMonkey 17 Objects are DOM. MXR ID Search for JSCLASS_IS_DOMJSCLASS JSCLASS_EMULATES_UNDEFINED Added in SpiderMonkey ...
JS_SetOptions
he two scripts "x = 1" and "var x = 1", where no variable x is in scope, do two different things. The former creates a property on the global object. The latter creates a property on obj. With this flag, both create a global property. MXR ID Search for JSOPTION_VAROBJFIX JSOPTION_PRIVATE_IS_NSISUPPORTS Mozilla extension. The context's private data points to an
XPCOM object (see nsISupports). This is only meaningful if SpiderMonkey is built with XPConnect. MXR ID Search for JSOPTION_PRIVATE_IS_NSISUPPORTS JSOPTION_COMPILE_N_GO Caller of JS_CompileScript et al promises to execute the compiled script once only, in the same scope object used for compilation. The caller may not modify objects on the scope chain between compilati...
Web Replay
d -- calling redirected library functions, using recorded locks or recorded atomics -- is disallowed at these times. There are some other areas where recorded events are also disallowed, such as during JS interrupt callbacks. Recording an event in one of these areas will fail a !AreThreadEventsDisallowed() assertion. These failures usually result from accessing a recorded lock or atomic. Core
xpcom and mozglue lock classes and mozilla::Atomic atomics are recorded by default, but many locks and atomics don't actually need to be recorded in order to correctly replay. Recording for a lock or atomic can be turned off by specifying recordreplay::Behavior::DontPreserve in either the lock's contructor argument or the atomic's template arguments. Interactions with the middleman process When reco...
Using the Places keywords API
the Add Keyword For this search contextual menu option in form text fields. Note this is the same feature previously known as Bookmark keywords, the key difference is that keywords are not bound to a specific bookmark, but to a specific URL. Using the keywords API The keywords API is a promise-based API available through the PlacesUtils module: Components.utils.import("resource://gre/modules/
XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", "resource://gre/modules/PlacesUtils.jsm"); Setting a keyword for an URL The insert() method accepts a keyword entry object describing the keyword to insert. It has the following properties: keyword: string representing the keyword url: either a URL or spec represeting the URL to associate to postData: optional POST data st...
Preferences API
s, including support for default preferences, user overrides via user.js, and locking. You can also create a XUL-based options window easily to allow user modify some preferences. Many applications including Firefox and Thunderbird have an additional tool for power users, about:config, which can be used to tweak the preferences without UI. Interfaces The preferences API is exposed as a set of
XPCOM components and interfaces: nsIPrefService, nsIPrefBranch. ... See also Code snippets:Preferences (more detailed discussion with multiple examples) ...
STEEL
terface that implements all the functions of extIApplication. The library has also been implemented in Firefox ("FUEL") and in SeaMonkey ("SMILE"). Objects extIApplication Objects extIApplication extIConsole extIEventItem extIEventListener extIEvents extIExtension extIExtensions extIPreference extIPreferenceBranch extISessionStorage steelIApplication Objects steelIApplication
XPCOM Although the STEEL steelIApplication object is preloaded into XUL scripts, it is not preloaded into JavaScript
XPCOM code. The object needs to be accessed like any other
XPCOM service: var Application = Components.classes["@mozilla.org/steel/application;1"].getService(Components.interfaces.steelIApplication); Other Resources STEEL development plan. bug 408370 bug 1278067 ...
extIExtension
Method overview FIXME: Attributes Attribute Type Description id readonly attribute AString The id of the extension. ...
extIPreferenceBranch
branch. The root branch is set based on the context of the owner. For example, an extension's preferences has a root of "extensions.extensionid.", while the application-level preferences have an empty root. All preference "aName" parameters used in this interface are relative to the root branch. extIPreferenceBranch is defined in toolkit/components/exthelper/extIApplication.idl. Implemented via
XPCOM service for extIApplication: see the instructions on the FUEL (Firefox), STEEL (Thunderbird) and SMILE (SeaMonkey) pages. Method overview boolean has(in AString aName) extIPreference get(in AString aName) nsIVariant getValue(in AString aName, in nsIVariant aDefaultValue) void setValue(in AString aName, in nsIVariant aValue) void reset() Attrib...
extISessionStorage
Method overview These methods are usually accessed via Application.storage. ...
XML Extras
The XML Extras module is built by default on all platforms, and is included in the browser installers so it is available in the nightly builds. ...
Binary compatibility
a new compiler without recompiling everything. Effectively, it is a different platform. What does this mean to you? If you build a component and it works fine in version 1.0 of Mozilla. If and when Mozilla upgrades the compiler they use, your component will have to be rebuilt against the same compiler. When you see a @status FROZEN, note that this means it should work as long as the component and
xpcom are built with the same compiler ABI. For more information on issues of componentization and binary compatibility, see http://mozilla.org/projects/
xpcom/gl...ent_Reuse.html . Comments and questions should be directed to the newsgroup, mozilla.dev.tech.
xpcom, or the mailing list, mozilla-
xpcom@mozilla.org. ...
mozilla::services namespace
To use it, you first need to include the header into your C++ file: #include "mozilla/Services.h" Then you can obtain references to services by simply accessing them from the mozilla::services namespace. ...
Components.classesByID
Components.classesByID is a read-only object whose properties are classes indexed by CID. Introduction Components.classesByID is a read-only object whose properties implement the nsIJSCID interface. Each property represents one of the classes of
XPCOM components that can be constructed or accessed as an
XPCOM service. Components.classesByID is exactly like Components.classes except that the elements are indexed by the canonical form of their CID, and does not only represent the component classes that have been registered with the component manager using a ContractID, but also those registered using a plain CID. Usage In order to retrieve the object for a given CID, you can use that CID as an index with Components.classesByID as follows: var clazz = Components.classesByID["{ed132c2...
Components.interfaces
Components.interfaces is a read-only object whose properties are interfaces indexed by their names. Introduction Components.interfaces is a read-only object whose properties implement the nsIJSIID interface. Each object represents one of the
XPCOM interfaces -- that some component or another might or might not implement. It reflects only those interfaces which have been designated in their .idl description as scriptable, that is the interfaces which XPConnect is capable of reflecting into JavaScript. Properties of the Components.interfaces object are used where
XPCOM methods expect a parameter of type nsID. This includes nsISupports.QueryInterface(), the optional parameter accepted by nsIJSCID.getService(), nsIJSCID.createInstance() when called from JavaScript, and nsIClassInfo.getIn...
Components.interfacesByID
It reflects only those interfaces which have been designated in their .idl description as [scriptable], i.e. the interfaces which XPConnect is capable of reflecting into JavaScript. ...
Components.isSuccessCode
Summary Determines whether a given
XPCOM return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively. Syntax var succeeded = Components.isSuccessCode(returnCode); Parameters returnCode The return code (of type nsresult) to be checked. Description Components.isSuccessCode() may be used to determine whether an
XPCOM return code (an nsresult) indicates success or failure. An
XPCOM return code indicates success if its high-order bit is 0, and it indicates failure if its high-order bit is 1. Note: A non-zero
XPCOM return code (that is, not NS_OK) does not necessarily indicate failure. Components.isSuccessCode() is functionally equivalent to the following JavaScript: function isSuccessCode(returnCode) { retur...
Components.lastResult
This is because failure result codes get converted by XPConnect into exceptions that are thrown into the calling JavaScript method. Most interfaces only return one success code -- NS_OK -- so Components.lastResult is rarely necessary. ...
Components.results
Components.results is a read-only object whose properties are the names listed as the first parameters of the macros in js/xpconnect/src/xpc.msg (also at Table Of Errors), with the value of each corresponding to that constant's value. Introduction Components.results is an object whose properties are the names of well-known
XPCOM result codes, with each value being that of the corresponding result code. Elements in this array can be used to test against unknown nsresult variables or they can be 'thrown' to indicate failure... if(something_unexpected_happened) throw Components.results.NS_ERROR_UNEXPECTED; The elements of the Components.results object can be enumerated using a for-in loop. Usage Implementing nsISupports The standard nsISupports is usually implemented in Java...
Components.utils
s() Specify a list of constructors to import into the scope. isXrayWrapper() Test whether a given object is an Xray or not. unload() Unloads a JS module loaded with import(). isDeadWrapper() Determines whether this object is backed by a DeadObjectProxy. lookupMethod() Looks up a native (i.e. declared in the interface) method or property of an
XPCOM object. Serves the same purpose as XPCNativeWrapper. makeObjectPropsNormal() Ensures that all functions come from the specified object's scope, and aren't cross-compartment wrappers. May only be called from JavaScript code. nondeterministicGetWeakMapKeys() Return the keys in a weak map. This operation is non-deterministic because it is affected by the scheduling of t...
Other Resources
Other Resources Embedding Mozilla XPConnect - Javascript-
XPCOM bridge BlackConnect - Java-
XPCOM bridge (no longer supported) XPIDL to Java types - from Blackconnect ...
Community
If you know of useful mailing lists, newsgroups, forums, or other communities related to Py
XPCOM, please link to them here. ActiveState Python
XPCOM bindings mailing list Discussion of the bindings between the Python language and the
XPCOM (cross-platform COM) technology from the Mozilla project. #py
xpcom on irc.mozilla.org Chat with other Py
XPCOM developers on Mozilla's IRC network. ...
Architecture basics
You can imagine it like a bridge between JavaScript code, and Mozilla guts. xpcshell is a command line interface to Mozilla JavaScript. It's an interactive interpreter -- it gives you a shell that talks straight to Mozilla, via JavaScript's XPConnect bridge into it. ...
Using components
Commonly, we start our scripts like so: var Cc = Components.classes; var Ci = Components.interfaces; If we want to get a hold of a component, we then do something like: var rc = Cc["@mozilla.org/registry;1"]; var rs = rc.getService(Ci.nsIRegistry); See also: xpcshell -- how to get a command line interface to JavaScript More Info As was already stated, it is common to start addon scripts like: var Cc = Components.classes; var Ci = Components.interfaces; There is also another way to start, which is exactly equivalent to the above. ...
XPConnect wrappers
somehow important, but they don't know when they should use what wrappers, or if they should be seeing a wrapper. Note: Wrappers can appear in the console log; for example "[object XrayWrapper [object blah]]". Because these are wrapped, you won't be able to peek down inside them from the console. Basic XPConnect objects XPCWrappedNative These objects are created when any natively implemented
XPCOM object (that is, any object implemented in C++) needs to be reflected into JavaScript. This includes all DOM objects (including Window) and chrome elements that are reflected into JavaScript. This wrapper is responsible for mapping calls from JavaScript into C++. This means that when you say window.focus(), you're calling into XPCWrappedNative code. If you call 'toString()' and get "[xpconnect ...
Profiling XPCShell
You could use Venkman for that. But sometimes, Venkman gives too much noise (because it also profiles chrome code). Or you might want to have a more reproducible testcase. In those cases, an xpcshell script can help. You can just call the code you want to test. But then, you can't use the Venkman UI. XPCTools There is profiler in the tree that can profile xpcshell scripts. ...
XPCShell Reference
s upon script completion. You can specify multiple JS files to execute by using multiple -f arguments, and the scripts will be executed in the order encountered. Furthermore, XPCShell looks for xpcshell.js in the current directory. If that file is found, it is executed before any other JS files specified. -g This option specifies which Gecko Runtime Environment directory (greDir) to use for
XPCOM. -i This option turns on the "interactive" mode -s This option toggles the JavaScript strict option on and off. By default it is off. -v version This allows you to specify a specific version of JS to use, and should be set to an integral value specified by the JSVersion enumerated type. For instance, specifying -v 180 will set the interpreter to use JavaScript version 1.8. -w (low...
nsCategoryManager
<<
XPCOM API Reference Summary The
XPCOM Category Manager. Class ID 16d222a6-1dd2-11b2-b693-f38b02c021b2 ContractID @mozilla.org/categorymanager;1 Supported Interfaces nsICategoryManager Remarks This component is a singleton and should therefore be accessed via the
XPCOM Service Manager. ...
nsDirectoryService
<<
XPCOM API Reference Summary The
XPCOM Directory Service. This service returns the locations of "well known" directories in an OS-independent manner. For instance, it can give you the path of the system's temporary directory, desktop directory, current working directory, and so on. Class ID f00152d0-b40b-11d3-8c9c-000064657374 ContractID @mozilla.org/file/directory_service;1 Supported Interfaces nsIProperties nsIDirectoryService Remarks This component is a singleton and should therefore be accessed via the
XPCOM Service Manager. Example Code #include "ns
XPCOM.h" #include "nsCOMPtr.h" #include "nsDirectoryServiceDefs.h" #include "nsIServiceManager.h" #include "nsIProperties.h" /** * Get the location of the system's "temp" directory. */ nsresult GetTempDir(...
nsScriptableInputStream
<<
XPCOM API Reference Summary A component implementing nsIScriptableInputStream. Class ID 7225c040-a9bf-11d3-a197-0050041caf44 ContractID @mozilla.org/scriptableinputstream;1 Supported Interfaces nsIScriptableInputStream, nsIInputStream Remarks This component should be accessed via the
XPCOM Component Manager. Example Code const nsIScriptableInputStream = Components.interfaces.nsIScriptableInputStream; function consumeStream(inputStream) { var factory = Components.classes["@mozilla.org/scriptableinputstream;1"]; var sis = factory.createInstance(nsIScriptableInputStream); sis.init(inputStream); try { while (true) { var chunk = sis.read(512); if (chunk.length == 0) break; // ok, chunk now contains a portion of the stream's da...
NS_GetMemoryManager
<<
XPCOM API Reference Summary The NS_GetMemoryManager function returns a reference to the
XPCOM Memory Manager. #include "ns
XPCOM.h" #include "nsIMemory.h" nsresult NS_GetMemoryManager( nsIMemory** aResult ); Parameters aResult [out] A reference to the
XPCOM Memory Manager. Return Values The NS_GetMemoryManager function returns NS_OK if successful. Otherwise, it returns an error code. Remarks The object returned is a singleton that is valid until NS_Shutdown
XPCOM is called. The interface pointer should be Release'd when it is no longer needed. Any code, intended to be used exclusively with Mozilla 1.8 and above, may use NS_Alloc, NS_Realloc, and NS_Free instead to access the
XPCOM Memory Manager's methods. History This function was finalized for Mozilla 0.9.7. Se...
NS_NewLocalFile
This path does not need to reference an existing file. It is an error to pass a relative filesystem path. aFollowLinks [in] This attribute will determine if the nsILocalFile instance will automatically resolve symbolic links. This parameter has no effect on UNIX systems. ...
NS_NewNativeLocalFile
This string should be encoded using ASCII or the multibyte character coding corresponding to the native filesystem. This path does not need to reference an existing file. It is an error to pass a relative filesystem path. aFollowLinks [in] This attribute will determine if the nsILocalFile instance will automatically resolve symbolic links. ...
NS_Realloc
<<
XPCOM API Reference Summary Reallocates a block of memory using the
XPCOM memory manager. #include "ns
XPCOM.h" void* NS_Realloc( void* aPtr, PRSize aSize ); Parameters aPtr [in] A pointer to the block of memory to reallocate. This pointer must have been previously allocated by the
XPCOM memory manager, or this parameter may be null in which case this function behaves like NS_Alloc. aSize [in] The size in bytes of the block to allocate, or zero if the given block is to be freed. Return Values This function returns a pointer to the allocated block of memory, which is suitably aligned for any kind of variable, or null if the allocation failed. Remarks This function provides a convenient way to access the
XPCOM memory manager. It is equivalent to calling realloc ...
nsresult
For a list of defined result values, see Error codes returned by Mozilla APIs. Note: On compilers that do not support strongly-typed enums (that is, compilers that don't support this feature of C++11), it falls back to being an unsigned 32-bit integer, as in past versions of Gecko. Note: Prior to Gecko 19.0, nsresult was not strongly typed. As a result, it was possible for code to misuse it, such as returning an nsresult value from a function whose signature indicates it returns a boolean. ...
Append
void Append( const self_type& aString ); Parameters aString [in] A nsACString to append to this string. void Append( const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to append to this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. Otherwise, aData need not be null terminated. void Append( char_type aChar ); Parameters aChar [in] A character to append to this string. ...
Assign
void Assign( const self_type& aString ); Parameters aString [in] A nsACString to copy into this string. void Assign( const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. Otherwise, aData need not be null terminated. void Assign( char_type aChar ); Parameters aChar [in] The character to copy into this string. ...
BeginReading
const char_type* BeginReading() const; Remarks The resulting character array is not necessarily null-terminated. The length of the array is determined by the result of the Length method. ...
Cut
void Cut( index_type aCutStart, size_type aCutLength ); Parameters aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. ...
EndReading
const char_type* EndReading() const; Remarks It is generally illegal to dereference the returned pointer, unless it is known that the string's internal buffer is null-terminated. The NS_CStringGetData function can be used to determine if a nsACString instance has null-terminated storage. Example Code See BeginReading for an example. ...
Insert
void Insert( const self_type& aString, index_type aPosition ); Parameters aString [in] A nsACString to append to this string. aPosition [in] An offset into the string's internal buffer specifying where to place the given characters. void Insert( const char_type* aData, index_type aPosition, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to append to this string. aPosition [in] An offset into the string's internal buffer specifying where to place the given characters. aDataLength [in] The length of aData, measured in storage units. ...
Length
<<
XPCOM API Reference Summary The Length function returns the number of storage units in the string's internal buffer (not including the null-terminator if present). size_type Length() const; ...
Replace
void Replace( index_type aCutStart, index_type aCutLength, const self_type& aString ); Parameters aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. aString [in] A nsACString to append to this string. void Replace( index_type aCutStart, size_type aCutLength, const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. ...
operator=
self_type& operator=( const self_type& aString ); Parameters aString [in] A nsACString to append to this string. Return Values This operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* aData ); Parameters aData [in] A raw character array to append to this string. Return Values This operator returns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type aChar ); Parameters aChar [in] A character to append to this string. Return Values This operator returns a reference back to the object being modified to allow operator chaining. ...
operator+=
self_type& operator+=( const self_type& aString ); Parameters aString [in] A nsACString to append to this string. Return Values This operator returns a reference back to the object being modified to allow operator chaining. self_type& operator+=( const char_type* aData ); Parameters aData [in] A raw character array to append to this string. Return Values This operator returns a reference back to the object being modified to allow operator chaining. self_type& operator+=( char_type aChar ); Parameters aChar [in] A character to append to this string. ...
Append
void Append( const self_type& aString ); Parameters aString [in] A nsAString to append to this string. void Append( const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to append to this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. Otherwise, aData need not be null terminated. void Append( char_type aChar ); Parameters aChar [in] A character to append to this string. ...
Assign
void Assign( const self_type& aString ); Parameters aString [in] A nsAString to copy into this string. void Assign( const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. Otherwise, aData need not be null terminated. void Assign( char_type aChar ); Parameters aChar [in] The character to copy into this string. ...
nsIBinaryInputStream
This might be used, for example, to implement network protocols or to read from architecture-neutral disk files, that is ones that can be read and written by both big-endian and little-endian platforms. ...
nsIBinaryOutputStream
This might be used, for example, to implement network protocols or to produce architecture-neutral binary disk files, that is ones that can be read and written by both big-endian and little-endian platforms. Output is written in big-endian order (high-order byte first), as this is traditional network order. ...
nsIBlocklistPrompt
1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void prompt([array, size_is(aCount)] in nsIVariant aAddons, [optional] in PRUint32 aCount); Methods prompt() Prompt the user about newly blocked addons. The prompt is then responsible for soft-blocking any addons that need to be afterwards. ...
nsIBlocklistService
xpcom/system/nsIBlocklistService.idlScriptable Please add a summary to this article. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 29 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26) Method overview unsigned long getAddonBlocklistState(in jsval addon, [optional] in AString appVersion, [optional] in AString toolkitVersion); unsigned long getPluginBlocklistState(in nsIPluginTag plugin, [optional] in AString appVersion, [optional] in AString toolkitVersion); boolean isAddonBlocklisted(in jsval addon, [optional] in AString appVersion, [optional] in AString toolkitVersion); Constants Constant Value Description STATE_NOT_BLOCKED 0 STATE_SOFTBLOCKED 1 ...
nsICategoryManager
Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Implemented by: @mozilla.org/categorymanager;1. ...
nsICollection
It provides basic operations on those items like: getting, setting, appending, removing, and so on. Inherits from: nsISerializable Last changed in Gecko 1.7 Method overview void AppendElement(in nsISupports item); void Clear(); PRUint32 Count(); nsIEnumerator Enumerate(); nsISupports GetElementAt(in PRUint32 index); void QueryElementAt(in PRUint32 index, in nsIIDRef uuid, [iid_is(uuid),retval] out nsQIResult result); void RemoveElement(in nsISupports item); void SetElementAt(in PRUint32 index, in nsISupports item); Methods AppendElement() Appends a new item to the collection. ...
nsIComponentManager
xpcom/components/nsIComponentManager.idlScriptable This interface provides methods to access factory objects and instantiate instances of classes. 66 Introduced Gecko 0.7 Inherits from: nsISupports Last changed in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5) Method overview void addBootstrappedManifestLocation(in nsILocalFile aLocation); void createInstance(in nsCIDRef aClass, in nsISupports aDelegate, in nsIIDRef aIID, [iid_is(aIID),retval] out nsQIResult result); void createInstanceByContractID(in string aContractID, in nsISupports aDelegate, in nsIIDRef aIID, [iid_is(aIID),retval] out nsQIResult result); void getClassObject(in nsCIDRef aClass, in nsIIDRef aIID, [iid_is(aIID),retval] out nsQIResult result); ...
nsIConsoleListener
Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void observe(in nsIConsoleMessage aMessage); Methods observe() Called by the nsIConsoleService when a message is posted to the console. Listeners must first be attached to the service using nsIConsoleService.registerListener() void observe( in nsIConsoleMessage aMessage ); Parameters aMessage The nsIConsoleMessage being posted. ...
nsIConsoleMessage
Inherits from: nsISupports Last changed in Gecko 1.7 Implementations may provide an object that can be Query Interfaced, nsISupports.QueryInterface(), to provide more specific message information. See nsIScriptError for an example. Attributes Attribute Type Description message wstring The message in a string format. [binaryname(MessageMoz)] Read only. ...
nsIConsoleService
It is used to log various messages, warnings, and errors and to obtain the logged messages. ...
nsIContentSecurityPolicy
content/base/public/nsIContentSecurityPolicy.idlScriptable Describes an
XPCOM component used to model and enforce Content Security Policies. 1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview boolean permitsAncestry(in nsIDocShell docShell); void refinePolicy(in AString policyString, in nsIURI selfURI); void scanRequestData(in nsIHttpChannel aChannel); void sendReports(in AString blockedURI, in AString violatedDirective); short shouldLoad(in unsigned long aContentType, in nsIURI aContentLocation, in nsIURI aRequestOrigin, in nsISupports aContext, in ACString aMimeTypeGuess, in nsISupports aExtra); short shouldProcess(in unsigned long aContentType, in nsIURI ...
nsIConverterInputStream
This allows reading unicode strings from a stream, automatically converting the bytes from a selected character encoding. 1.0 66 Introduced Gecko 1.8 Inherits from: nsIUnicharInputStream Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Implemented by: @mozilla.org/intl/converter-input-stream;1. ...
nsIConverterOutputStream
1.0 66 Introduced Gecko 1.8 Inherits from: nsIUnicharOutputStream Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Implemented by: @mozilla.org/intl/converter-output-stream;1. To create an instance, use: var converterOutputStream = Components.classes["@mozilla.org/intl/converter-output-stream;1"] .createInstance(Components.interfaces.nsIConverterOutputStream); Method overview void init(in nsIOutputStream aOutStream, in string aCharset, in unsigned long aBufferSize, in PRUnichar aReplacementCharacter); Methods init() Initialize this stream. ...
nsICrashReporter
1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void annotateCrashReport(in ACString key, in ACString data); void appendAppNotesToCrashReport(in ACString data); void appendObjCExceptionInfoToAppNotes(in voidPtr aException); Native code only! void writeMinidumpForException(in voidPtr aExceptionInfo); Native code only! Attributes Attribute Type Description enabled boolean Enable or disable the crashreporter at runtime. minidumpPath nsILocalFile Get or set the path on the local system to which minidumps will be written when a crash happens. ...
nsICycleCollectorListener
1.0 66 Introduced Gecko 2.0 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) The order of calls will be call to begin(); then for every node in the graph a call to noteObject() and calls to noteEdge() for every edge starting at that node; then a call to beginDescriptions(); then for every black node in the cycle collector graph a call to either describeRefcountedObject() or to describeGCedObject(); and then a call to end(). If begin() returns an error none of the other functions will be called. ...
nsIMsgDBView
Inherits from: nsISupports Implemented by: @mozilla.org/messenger/msgdbview;1. To create an instance, use: var dbView = Components.classes[@mozilla.org/messenger/msgdbview;1?type=] .createInstance(Components.interfaces.nsIMsgDBView); where type designates different types of view's available. ...
nsIMutableArray
Inherits from: nsIArray Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Consumers of nsIArray should not QueryInterface to nsIMutableArray unless they own the array. As above, it is legal to add null elements to the array. Note also that null elements can be created as a side effect of insertElementAt(). Conversely, if insertElementAt() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsIArray.queryElementAt() will never return a null value. ...
nsIOutputStream
Inherits from: nsISupports Last changed in Gecko 1.0 An output stream may be "blocking" or "non-blocking" (see the IsNonBlocking() method). A blocking output stream may suspend the calling thread in order to satisfy a call to Close(), Flush(), write(), writeFrom(), or writeSegments(). A non-blocking output stream, on the other hand, must not block the calling thread of execution. Note: Blocking output streams are often written to on a background thread to avoid locking up the main application thread. For this reason, it is generally the case that a blocking output stream should be implemented using thread-safe AddRef and Release. ...
nsIOutputStreamCallback
Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void onOutputStreamReady(in nsIAsyncOutputStream aStream); Methods onOutputStreamReady() Called to indicate that the stream is either writable or closed. void onOutputStreamReady( in nsIAsyncOutputStream aStream ); Parameters aStream The stream whose nsIAsyncOutputStream.asyncWait() method was called. ...
nsIPipe
Inherits from: nsISupports Last changed in Gecko 1.6 Method overview void init(in boolean nonBlockingInput, in boolean nonBlockingOutput, in unsigned long segmentSize, in unsigned long segmentCount, in nsIMemory segmentAllocator); Attributes Attribute Type Description inputStream nsIAsyncInputStream The pipe's input end, which also implements nsISearchableInputStream. Read only. outputStream nsIAsyncOutputStream The pipe's output end. Read only. Methods init() initialize this pipe. ...
nsIPrefBranch2
anch to hold a reference to the observer) and holds a reference to the branch object for the purpose of getting/setting preference values. There are 3 approaches which have been implemented in an attempt to avoid these situations: The nsPrefBranch object supports nsISupportsWeakReference. Any consumer may hold a weak reference to it instead of a strong one. The nsPrefBranch object listens for
xpcom-shutdown and frees all of the objects currently in its observer list. This ensures that long lived objects (services for example) will be freed correctly. The observer can request to be held as a weak reference when it is registered. This insures that shorter lived objects (say one tied to an open window) will not fall into the cyclical reference trap. The list of registered observers may be c...
nsIProcess
Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Implemented by: @mozilla.org/process/util;1. ...
nsIProcess2
This expands upon the nsIProcess interface. 1.0 66 Introduced Gecko 1.9.1 Obsolete Gecko 1.9.2 Inherits from: nsIProcess Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Gecko 1.9.2 note This interface was removed in Gecko 1.9.2 and its method added to nsIProcess. Implemented by: @mozilla.org/process/util;1. ...
nsIProgrammingLanguage
Inherits from: nsISupports Last changed in Gecko 0.9.5 Constants Identifiers for programming languages. Constant Value Description UNKNOWN 0 CPLUSPLUS 1 C++ JAVASCRIPT 2 JavaScript PYTHON 3 Python PERL 4 Perl JAVA 5 Java ZX81_BASIC 6 ZX81 Basic JAVASCRIPT2 7 JavaScript 2 RUBY 8 Ruby PHP 9 PHP TCL 10 TCL MAX 10 This will be kept at the largest index. ...
nsIProperty
Inherits from: nsISupports Last changed in Gecko 1.7 Attributes Attribute Type Description name AString Get the name of the property. Read only. value nsIVariant Get the value of the property. Read only. ...
nsIPropertyBag2
xpcom/ds/nsIPropertyBag2.idlScriptable This interface extends nsIPropertyBag with some methods for getting properties in specific formats. Inherits from: nsIPropertyBag Last changed in Gecko 1.0 Method overview nsIVariant get(in AString prop); ACString getPropertyAsACString(in AString prop); AString getPropertyAsAString(in AString prop); AUTF8String getPropertyAsAUTF8String(in AString prop); boolean getPropertyAsBool(in AString prop); double getPropertyAsDouble(in AString prop); PRInt32 getPropertyAsInt32(in AString prop); PRInt64 getPropertyAsInt64(in AString prop); void getPropertyAsInterface(in AString prop, in nsIIDRef iid, [iid_is(iid), retval] out nsQIResult result); PRUint32 getProp...
nsIPropertyElement
Inherits from: nsISupports Last changed in Gecko 1.0 Attributes Attribute Type Description key AUTF8String The key used to refer to this property. value AString The string value stored for this property. ...
nsIProtocolProxyService
able at runtime (perhaps via the preferences service). void registerFilter( in nsIProtocolProxyFilter aFilter, in unsigned long aPosition ); Parameters aFilter The nsIProtocolProxyFilter instance to be registered. aPosition The position of the filter. unregisterFilter() This method may be used to unregister a proxy filter instance. All filters will be automatically unregistered at
XPCOM shutdown. void unregisterFilter( in nsIProtocolProxyFilter aFilter ); Parameters aFilter The nsIProtocolProxyFilter instance to be unregistered. See also nsIProxyInfo nsIProtocolProxyFilter nsIProxiedProtocolHandler nsICancelable ...
nsIPushService
sh", scriptSecurityManager.getSystemPrincipal(), (code, ok) => { if (!Components.isSuccessCode(code)) { Cu.reportError("Error unsubscribing: " + code); return; } // `ok === true` if the subscription was removed, or `false` if the // `(scope, principal)` pair didn't have a subscription. } ); Receiving Push Messages Subscriptions created from privileged code use
XPCOM observer notifications instead of service worker events. You can use the global nsIObserverService to listen for these notifications. Messages sent to system subscriptions are broadcasted to all push-message observers. Your nsIObserver should ensure the data parameter matches your subscription scope. Otherwise, your code may try to handle messages meant for other subscriptions. Topic...
nsIScriptableInputStream
Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview unsigned long available(); void close(); void init(in nsIInputStream aInputStream); string read(in unsigned long aCount); ACString readBytes(in unsigned long aCount); Methods available() Return the number of bytes currently available in the stream. Note: This method should not be used to determine the total size of a stream, even if the stream corresponds to a local file. ...
nsIThreadObserver
The nsIThreadObserver interface may be implemented to let an observer implement a layered event queue. The implementation of this interface must be thread safe.
xpcom/threads/nsIThreadInternal.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsISupports Method overview void afterProcessNextEvent(in nsIThreadInternal thread, in unsigned long recursionDepth); void onDispatchedEvent(in nsIThreadInternal thread); void onProcessNextEvent(in nsIThreadInternal thread, in boolean mayWait, in unsigned long recursionDepth); Methods afterProcessNextEvent() Called by the nsIThread method nsIThread.ProcessNextEvent() after an event is processed. This method is only called on the target thread. Note: I...
nsIThreadPool
1.0 66 Introduced Gecko 1.9 Inherits from: nsIEventTarget Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) A thread pool provides a convenient way to process events off the main thread. When you send events to the thread pool, the pool creates a new thread to process the event, up to the number of threads specified by the threadLimit attribute. Method overview void shutdown(); Attributes Attribute Type Description idleThreadLimit unsigned long Get/set the maximum number of idle threads that are kept alive. ...
nsIThreadPoolListener
Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Inherits from: nsISupports Method overview void onThreadCreated(); void onThreadShuttingDown(); Methods onThreadCreated() Called when a new thread is created by the thread pool. The notification happens on the newly created thread. void onThreadCreated(); Parameters None. onThreadShuttingDown() Called when a new thread is about to be destroyed by the thread pool. ...
nsITimer
ied delay. Note that the delay is approximate: the timer can be fired before the requested time has elapsed. nsITimer instances must be initialized by calling one of the initialization methods. You may also re-initialize (using one of the initialization methods) an existing instance to avoid the overhead of destroying and creating a timer. It is not necessary to cancel the timer in that case.
xpcom/threads/nsITimer.idlScriptable Please add a summary to this article. Last changed in Gecko 5 (Firefox 5 / Thunderbird 5 / SeaMonkey 2.2) Inherits from: nsISupports Implemented by: @mozilla.org/timer;1. To create an instance, use: var timer = Components.classes["@mozilla.org/timer;1"] .createInstance(Components.interfaces.nsITimer); Users of instances of nsITimer should ke...
nsITimerCallback
Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void notify(in nsITimer timer); Methods notify() Initialize a timer to fire after the given millisecond interval. This version takes a function to call and a closure to pass to that function. ...
nsIUTF8StringEnumerator
Inherits from: nsISupports Last changed in Gecko 1.7 Method overview AUTF8String getNext(); boolean hasMore(); Methods getNext() Returns the next string in the enumerator. The "next" element is the first string upon the first call. Must be preceded by a call to hasMore(), which returns PR_TRUE. This method is generally called within a loop to iterate over the strings in the enumerator. AUTF8String getNext(); Parameters None. Return value The next string in the enumerator. Throws an exception if there are no more strings. ...
nsIUUIDGenerator
1.0 66 Introduced Gecko 1.8.1 Inherits from: nsISupports Last changed in Gecko 1.8.1 (Firefox 2 / Thunderbird 2 / SeaMonkey 1.1) Implemented by @mozilla.org/uuid-generator; as a service: var uuidGenerator = Components.classes["@mozilla.org/uuid-generator;1"] .getService(Components.interfaces.nsIUUIDGenerator); Method overview nsIDPtr generateUUID(); void generateUUIDInPlace(in nsNonConstIDPtr id); Native code only! Methods generateUUID() Obtains a new UUID using appropriate platform-specific methods to obtain a nsID that can be considered to be globally unique. ...
nsIUpdateTimerManager
al The length of time, in seconds, until the timer should fire. Remarks Note that the timer is not precise, and that the default minimum interval is 2 minutes. ...
nsIWeakReference
It allows a consumer to hold an indirect, non-owning reference to an
XPCOM object. Inherits from: nsISupports Last changed in Gecko 0.9.9 An instance of nsIWeakReference is a proxy object that cooperates with its referent to give clients a non-owning, non-dangling reference. Clients own the nsIWeakReference instance. ...
nsIWebNavigationInfo
o change, so that boolean tests can be done on the return value if isTypeSupported to detect whether a type is supported at all. IMAGE 1 Returned by isTypeSupported() to indicate that a type is supported as an image. PLUGIN 2 Returned by isTypeSupported() to indicate that a type is supported via an NPAPI ("Netscape 4 API") plug-in. This is not the value returned for "
XPCOM plug-ins". OTHER 1 << 15 Note: Other return types may be added here in the future as they become relevant. Returned by isTypeSupported() to indicate that a type is supported via some other means. Methods isTypeSupported() Determines whether or not the specified MIME type is supported by the given nsIWebNavigation object. This lets you determine whether a MIME type ca...
nsIWindowsRegKey
1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) The interface represents a single key in the registry. This interface is highly Win32 specific. ...
nsIWritablePropertyBag
1.0 66 Introduced Gecko 1.8 Inherits from: nsIPropertyBag Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview void deleteProperty(in AString name); void setProperty(in AString name, in nsIVariant value); Methods deleteProperty() Delete a property with the given name. void deleteProperty( in AString name ); Parameters name Property to delete. Exceptions thrown NS_ERROR_FAILURE If a property with that name doesn't exist. setProperty() Set a property with the given name to the given value. If a property already exists with the given name, it is overwritten. ...
nsIWritablePropertyBag2
xpcom/ds/nsIWritablePropertyBag2.idlScriptable This interface extends nsIPropertyBag2 with methods for setting properties. 1.0 66 Introduced Gecko 1.8 Inherits from: nsIPropertyBag2 Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method overview void setPropertyAsACString(in AString prop, in ACString value); void setPropertyAsAString(in AString prop, in AString value); void setPropertyAsAUTF8String(in AString prop, in AUTF8String value); void setPropertyAsBool(in AString prop, in boolean value); void setPropertyAsDouble(in AString prop, in double value); void setPropertyAsInt32(in AString prop, in PRInt32 value); void setPropertyAsInt64(in AString prop, in PRInt64 value); ...
nsIXMLHttpRequest
r a Mozilla add-on developer, please refer to the XMLHttpRequest documentation instead. This page contains documentation, specific to Mozilla application and add-on developers. The interface definition: //github.com/RealityRipple/UXP/blob/master/dom/xhr/nsIXMLHttpRequest.idl Elevated Privileges As mentioned in the "Non-Standard Properties" the property of channel was read-only. When using the
XPCOM interface, as seen below in Example 2, we can get access to this. The most obvious benefit is that we can set nsiRequest - Constants in the xhr.channel.loadFlags. For instance, as done in Example 2, the flag of LOAD_ANONYMOUS is added, this strips all user data (cookies, tokens, etc). Using event handlers from native code (Not sure if it's up-to-date) From native code, the way to set up onload...
nsIXPCException
js/src/xpconnect/idl/xpcexception.idlScriptable These exception objects are the preferred types of exceptions when implementing
xpcom interfaces in JavaScript. Inherits from: nsIException Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Method overview void initialize(in string aMessage, in nsresult aResult, in string aName, in nsIStackFrame aLocation, in nsISupports aData, in nsIException aInner); xpcexJSVal stealJSVal(); Native code only! void stowJSVal(in xpcexJSContextPtr cx, in xpcexJSVal val); Native code only! Methods initialize() void initialize( in string aMessage, in nsresult aResult, in string aName, in nsIStackFrame aLocation, in nsISupports aData, in nsIException aInner ); Parameters aMessage aResult aName aLocatio...
nsIXPCScriptable
For example, callers must guarantee that they set the *_retval of the various methods that return a boolean to PR_TRUE before making the call. Implementations may skip writing to *_retval unless they want to return PR_FALSE. js/src/xpconnect/idl/nsIXPCScriptable.idlNot scriptable Please add a summary to this article. ...
nsIXULAppInfo
It can be used to distinguish between different Mozilla-based applications. It provides application name, application version, Gecko version and more. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) In XULRunner applications nsIXULAppInfo obtains app-specific information from application.ini. Implemented by: @mozilla.org/xre/app-info;1. To create an instance, use: var xulAppInfo = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULAppInfo); The nsIXULRuntime interface is also implemented by "xre/app-info". ...
nsIXmlRpcClient
rray or nsIDictionary. 'base64' isn't supported. No QueryInterface call is needed, the object has been QueryInterfaced to the correct interface. void createType ( in unsigned long type, out nsIIDRef uuid, [iid_is(uuid),retval] out nsQIResult result ) ; Parameters type One of the listed constants. uuid The uuid of the returned object. No QI call needed. result The appropriate
XPCOM object. ...
nsIZipWriter
s it for (var i=0; i<dirArr.length; i++) { Cu.reportError('adding contents of dir['+i+']: ' + dirArr[i].leafName + ' PATH: ' + dirArr[i].path); var dirEntries = dirArr[i].directoryEntries; while (dirEntries.hasMoreElements()) { var entry = dirEntries.getNext().QueryInterface(Ci.nsIFile); //entry is instance of nsiFile so here https://developer.mozilla.org/docs/
XPCOM_Interface_Reference/nsIFile if (entry.path == xpi.path) { Cu.reportError('skipping entry - will not add this entry to the zip file - as this is the zip itself: "' + xpi.path + '" leafName:"' + xpi.leafName + '"'); continue; } if (entry.isDirectory()) { dirArr.push(entry); } var relPath = entry.path.replace(dirArr[0].p...
NS_ASSERTION
An assertion failure should be thrown on critical program errors only. A triggered assertion failure is equivalent to crashing in Tinderbox tests. ...
NS_CStringAppendData
This is a low-level API. #include "nsStringAPI.h" nsresult NS_CStringAppendData( nsACString& aString, const char* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsACString instance to be modified. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. Otherwise, aData need not be null-terminated. Return Values The NS_CStringAppendData function returns NS_OK if successful. Otherwise, it returns an error code. ...
NS_CStringCloneData
#include "nsStringAPI.h" char* NS_CStringCloneData( const nsACString& aString ); Parameters aString [in] A nsACString instance whose data is to be cloned. Return Values The NS_CStringCutData function returns a pointer to a null-terminated, heap allocated buffer on success. On failure it returns nsnull. The resulting buffer may be freed by calling nsMemory::Free. History This function was frozen for Mozilla 1.7. See bug 239716 for details. ...
NS_CStringContainerFinish
#include "nsStringAPI.h" void NS_CStringContainerFinish( nsCStringContainer& aString ); Parameters aString [in] A nsCStringContainer instance that is no longer needed. History This function was finalized for Mozilla 1.7. See bug 239123 for details. ...
NS_CStringContainerInit
#include "nsStringAPI.h" nsresult NS_CStringContainerInit( nsCStringContainer& aString ); Parameters aString [in] A nsCStringContainer instance to be initialized. Return Values The NS_CStringContainerInit function returns NS_OK if successful. Otherwise, it returns an error code. Remarks This function is equivalent to NS_CStringContainerInit2(container, nsnull, 0, 0). The nsCStringContainer structure has private members that should not be accessed directly. After a nsCStringContainer object has been initialized via NS_CStringContainerInit, it may be used as an ordinary nsACString object. ...
NS_CStringCopy
This is a low-level API. #include "nsStringAPI.h" nsresult NS_CStringCopy( nsACString& aDestString, const nsACString& aSrcString ); Parameters aDestString [in] A nsACString instance to be modified. aSrcString [in] A nsACString instance containing the new string value. Return Values The NS_CStringCopy function returns NS_OK if successful. Otherwise, it returns an error code. Remarks This function is designed to allow the implementation to efficiently assign the same value to two string objects. The implementation may employ reference counting techniques to optimize this operation. ...
NS_CStringCutData
This is a low-level API. #include "nsStringAPI.h" nsresult NS_CStringCutData( nsACString& aString, PRUint32 aCutStart, PRUint32 aCutLength ); Parameters aString [in] A nsACString instance to be modified. aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. Pass PR_UINT32_MAX to specify the length from aCutStart to the end of the string. Return Values The NS_CStringCutData function returns NS_OK if successful. Otherwise, it returns an error code. ...
NS_CStringGetData
#include "nsStringAPI.h" PRUint32 NS_CStringGetData( const nsACString& aString, const char** aData, PRBool* aTerminated = nsnull ); Parameters aString [in] A nsACString instance to inspect. aData [out] A const pointer to the string's internal buffer. aTerminated [out] This optional result parameter indicates whether or not aData is null-terminated. It may be null if the caller is not interested in this information. Return Values The NS_CStringGetData function returns the length of aData, measured in storage units (bytes). Example Code // Count the number of times a particular character appears in a string. ...
NS_CStringGetMutableData
#include "nsStringAPI.h" PRUint32 NS_CStringGetMutableData( nsACString& aString, PRUint32 aDataLength, char** aData ); Parameters aString [in] A nsACString instance to modify. aDataLength [in] The number of characters to resize the string's internal buffer to or PR_UINT32_MAX to return the buffer as-is. aData [out] Upon return, if the function was successful, then *aData references the string's internal buffer. Return Values This function returns the number of characters contained in the string's internal buffer (excluding any null-terminator). ...
NS_CStringInsertData
This is a low-level API. #include "nsStringAPI.h" nsresult NS_CStringInsertData( nsACString& aString, PRUint32 aOffset, const char* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsACString instance to be modified. aOffset [in] An offset into the string's internal buffer specifying where to place the given characters. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. Otherwise, aData need not be null terminated. ...
NS_CStringSetData
This is a low-level API. #include "nsStringAPI.h" nsresult NS_CStringSetData( nsACString& aString, const char* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsACString instance to modify. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. Otherwise, aData need not be null-terminated. Return Values The NS_CStringSetData function returns NS_OK if successful. Otherwise, it returns an error code. ...
NS_CStringSetDataRange
This is a low-level API. #include "nsStringAPI.h" nsresult NS_CStringSetDataRange( nsACString& aString, PRUint32 aCutStart, PRUint32 aCutLength, const char* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsACString instance to modify. aCutStart [in] The starting index of the section to replace, measured in storage units. aCutLength [in] The length of the section to replace, measured in storage units. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. ...
NS_CStringToUTF16
#include "nsStringAPI.h" nsresult NS_CStringToUTF16( const nsACString& aSrc, nsCStringEncoding aSrcEncoding, nsAString& aDest ); Parameters aSrc [in] A nsACString instance containing the source string to be converted. aSrcEncoding [in] The character encoding of the source string. See nsCStringEncoding for the set of values that can be passed for this parameter. aDest [out] A nsAString instance that will contain the result of the conversion. The result will be encoded using the host byte order. Return Values The NS_CStringToUTF16 function returns NS_OK if successful. ...
NS_StringAppendData
This is a low-level API. #include "nsStringAPI.h" nsresult NS_StringAppendData( nsAString& aString, const PRUnichar* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsAString instance to be modified. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. Otherwise, aData need not be null terminated. Return Values The NS_StringAppendData function returns NS_OK if successful. Otherwise, it returns an error code. ...
NS_StringCloneData
#include "nsStringAPI.h" PRUnichar* NS_StringCloneData( const nsAString& aString ); Parameters aString [in] A nsAString instance whose data is to be cloned. Return Values The NS_StringCutData function returns a pointer to a null-terminated, heap allocated buffer on success. On failure it returns nsnull. The resulting buffer may be freed by calling nsMemory::Free. History This function was frozen for Mozilla 1.7. See bug 239716 for details. ...
NS_StringContainerFinish
This is a low-level API. #include "nsStringAPI.h" void NS_StringContainerFinish( nsStringContainer& aString ); Parameters aString [in] A nsStringContainer instance that is no longer needed. Return Values This function does not return a value. Example Code See NS_StringContainerInit for an example. History This function was frozen for Mozilla 1.7. See bug 239123 for details. ...
NS_StringContainerInit
This is a low-level API. #include "nsStringAPI.h" nsresult NS_StringContainerInit( nsStringContainer& aString ); Parameters aString [in] A nsStringContainer instance to be initialized. Return Values The NS_StringContainerInit function returns NS_OK if successful. Otherwise, it returns an error code. Remarks The nsStringContainer structure has unspecified size and layout. Its members may not be accessed directly. After a nsStringContainer object has been initialized, it may be used as an ordinary nsAString object. The internal buffer allocated by a nsStringContainer is always null-terminated. ...
NS_StringCopy
This is a low-level API. #include "nsStringAPI.h" nsresult NS_StringCopy( nsAString& aDestString, const nsAString& aSrcString ); Parameters aDestString [in] A nsAString instance to be modified. aSrcString [in] A nsAString instance containing the new string value. Return Values The NS_StringCopy function returns NS_OK if successful. Otherwise, it returns an error code. Remarks This function is designed to allow the implementation to efficiently assign the same value to two string objects. The implementation may employ reference counting techniques to optimize this operation. ...
NS_StringCutData
This is a low-level API. #include "nsStringAPI.h" nsresult NS_StringCutData( nsAString& aString, PRUint32 aCutStart, PRUint32 aCutLength ); Parameters aString [in] A nsAString instance to be modified. aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. Pass PR_UINT32_MAX to specify the length from aCutStart to the end of the string. Return Values The NS_StringCutData function returns NS_OK if successful. Otherwise, it returns an error code. Remarks This function is defined inline as a wrapper around NS_StringSetDataRange. ...
NS_StringGetData
This is a low-level API. #include "nsStringAPI.h" PRUint32 NS_StringGetData( const nsAString& aString, const PRUnichar** aData, PRBool* aTerminated ); Parameters aString [in] A nsAString instance to inspect. aData [out] A const pointer to the string's internal buffer. aTerminated [out] This optional result parameter indicates whether or not aData is null-terminated. Return Values The NS_StringGetData function returns the length of aData, measured in storage units (bytes). ...
NS_StringInsertData
This is a low-level API. #include "nsStringAPI.h" nsresult NS_StringInsertData( nsACString& aString, PRUint32 aOffset, const PRUnichar* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsACString instance to be modified. aOffset [in] An offset into the string's internal buffer specifying where to place the given characters. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. Otherwise, aData need not be null terminated. ...
NS_StringSetData
This is a low-level API. #include "nsStringAPI.h" nsresult NS_StringSetData( nsAString& aString, const PRUnichar* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsAString instance to modify. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated. Otherwise, aData need not be null terminated. Return Values The NS_StringSetData function returns NS_OK if successful. Otherwise, it returns an error code. ...
NS_StringSetDataRange
This is a low-level API. #include "nsStringAPI.h" nsresult NS_StringSetDataRange( nsAString& aString, PRUint32 aCutStart, PRUint32 aCutLength, const PRUnichar* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsAString instance to modify. aCutStart [in] The starting index of the section to replace, measured in storage units. aCutLength [in] The length of the section to replace, measured in storage units. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. ...
NS_UTF16ToCString
#include "nsStringAPI.h" nsresult NS_UTF16ToCString( const nsAString& aSrc, nsCStringEncoding aDestEncoding, nsACString& aDest ); Parameters aSrc [in] A nsAString instance containing the source UTF-16 string to be converted. The source string should be encoded using the host byte order. aDestEncoding [in] The character encoding of the destination string. See nsCStringEncoding for the set of values that can be passed for this parameter. aDest [out] A nsACString instance that will contain the result of the conversion. ...
nsStaticModuleInfo
Summary This data structure is used by NS_Init
XPCOM3 to specify static
XPCOM modules. #include "ns
XPCOM.h" struct nsStaticModuleInfo { const char* name; nsGetModuleProc getModule; }; Members name This member provides the name of the module as a null-terminated, ASCII-valued character array. getModule This member provides a function pointer of type nsGetModuleProc that returns a nsIModule instance. ...
Storage
extensions and Firefox components only. The API is currently "unfrozen", which means it is subject to change at any time; in fact, it has changed somewhat with each release of Firefox since it was introduced, and will likely continue to do so for a while. Note: Storage is not the same as the DOM:Storage feature which can be used by web pages to store persistent data or the Session store API (an
XPCOM storage utility for use by extensions). Getting started This document covers the Storage API and some peculiarities of SQLite. It does not cover SQL or "regular" SQLite. You can find some very useful links in the See also section however. For Storage API help, you can post to mozilla.dev.apps.platform on the news server news.mozilla.org. To report bugs, use Bugzilla. The overall procedure for ...
Status, Recent Changes, and Plans
aw pointer (or a literal 0 or nsnull) work correctly on all compilers. See bug 65664. Made getter_AddRefs( nsCOMPtr& ) apply the same type-safety check that the simple assignment forms do. Added do_CreateInstance. Added do_GetService. Eliminated the need to cast getter_AddRefs when an nsISupports** is needed. Relaxed the invariant for nsCOMPtr<nsISupports>, so that it is now a pointer to any
XPCOM interface. Added do_QueryReferent to make using nsIWeakReferences easier. Plans for nsCOMPtr bug 59212: as soon as we test on more compilers, start recommending already_AddRefed as a function result. bug 59414: making operator& private may help prevent some leaks caused by casting Move the factored nsCOMPtr routines into their own library, to reduce nsCOMPtr clients' dependency on the XPC...
Using nsCOMPtr
If you've never used nsCOMPtr before, you're starting in the right place. Just keep reading. You'll know when to stop. ...
Using nsIClassInfo
How do I use it? If you're writing JavaScript code which uses a C++ class implementing nsIClassInfo, you don't need to do anything to activate the auto-interface magic which makes calling QueryInterface unnecessary. ...
Working with out parameters
void getTransferData ( in string aFlavor, out nsISupports aData, out unsigned long aDataLen ) ; ... } The getTransferData method takes three parameters, aFlavor, aData, and aDataLen, and returns nothing. aData and aDataLen are marked as out, meaning that they act as "return values" for this method, and are changed during the method call. These are so-called out parameters. Usage In order to use such a method from JavaScript via XPConnect, you have to follow a specific rule. To get at the out parameters, you have to pass in an object. ...
already_AddRefed
You may want to use this as a return type from a function that has already produced an AddRefed pointer as a result. In fact, it is preferred to use already_AddRefed in this case over returning a raw pointer or nsCOMPtr (see the nsCOMPtr user manual). Defined in: mfbt/AlreadyAddRefed.h. Example ... already_AddRefed<nsIFoo> GetFoo() { nsIFoo* foo = mFoo; NS_IF_ADDREF(foo); return foo; } // or already_AddRefed<nsIFoo> GetFoo() { nsCOMPtr<nsIFoo> foo = mFoo; // ... return foo.forget(); } ... // The following assignment doesn't perform an additional AddRef, // as it would do if GetFoo() returned a raw pointer. ...
nsCOMPtr versus RefPtr
llows: do_QueryObject inherits from nsCOMPtr_helper, so it can be assigned into both nsCOMPtr and RefPtr. The downside of this inheritance is that do_QueryObject requires an extra virtual call to operator() in the helper method. do_QueryObject is templated on the argument type, so it's possible to pass in objects that multiply inherit from nsISupports. However, when the destination type is an
XPCOM interface, it's probably better to static_cast to a class that unambiguously inherits from nsISupports and use do_QueryInterface in such cases. ...
Xptcall Porting Status
r a long time now. <font color="white">Done</font> OpenVMS Alpha Colin R. Blake <colin@theblakes.com> Colin says this is passing all the tests on OpenVMS Alpha! <font color="white">Done</font> NT Alpha bob meader <bob@guiduck.com> bob writes: Enclosed is xptcall for alpha/nt target.. It is a variation of the IRIS port (only targeted for win32). Notice the last 2 files (the change to mozilla\
xpcom\build\makefile.win and mozilla\
xpcom\build) are needed because I was unable to figure how to do a "declspecexport" from the assembler ASAXP ... if some knows how to do that then those last 2 files won't be needed. I have had someone look over this code at bridge.com (the entry point to compaq/gem compiler team) and this code was given the OK. I consider it "done". This code lives in the files whe...
pyxpidl
The newer utility has the advantage of not needing any code to be compiled in order to use it, and let us remove a bunch of old code from the tree. pyxpidl has been in use for a while, but replaced xpidl in the Gecko SDK starting in Gecko 9.0. Using pyxpidl pyxpidl is in the SDK in the sdkdir/sdk/bin/ directory. ...
xpidl
xpidl is a tool for generating
XPCOM interface information, based on XPIDL interface description files. It generates: C++ header files (.h), with a commented template for full C++ implementation of the interface XPConnect typelib files (.xpt), with runtime type information to dynamically call
XPCOM objects through XPConnect Note: Starting in Gecko 9.0, xpidl has been replaced with pyxpidl in the Gecko SDK. pyxpidl has been used for some time now, but now this older tool has been fully retired. xpidl is based on the libIDL idl compiler from the Gnome project. The libIDL compiler depends on glib, also from the Gnome project. The xpidl compiler is now part of the build process, allowing us to generate headers used by the
XPCOM components. Please check the Build Documentation for f...
XTF
For example, the Mozilla XForms Project uses XTF to add support for the XForms namespace. Documentation XTF Readme The XTF readme. XTF Home The XTF home (outdated). XTF: When XBL Just Won't Cut It More recent primer to XTF by Alex Vincent. Extending Gecko with XBL and XTF A presentation given at XTech 2005 comparing XBL and XTF, as well as discussing XTF basics. View All... ...
Creating a gloda message query
a GlodaFolder instance. conversation: The conversation the message belongs to, as represented by a GlodaConversation instance. Somewhat magic attributes: headerMessageID: The contents of the Message-ID header of the message. You probably should not be using this. folderMessage: Return the nsIMsgDBHdr that corresponds to the message. An nsIMsgDBHdr is the low-level, old-school, Thunderbird
XPCOM representation of a message. You should not need to use this unless you are dealing with other old-school code or you need to manipulate the state of a message. In the future, the STEEL layer should provide wrappers to make manipulation clean and fun. Note that this message may return "null" if gloda is unable to locate the underlying message anymore. Attributes provided by fundattr.js: from...
Message Interfaces
related header information for a mail message. nsIMsgDBHdr nsIMsgDBHdr - this interface describes headers for mail messages. It is a child of nsIMsgHdr (see above). nsIMsgThread nsIMsgThread - this interface is used to interact with threads in Thunderbird. nsIMsgDBView nsIMsgDBView - The nsIMsgDBView interface handles the display of mail in the threadpane and preview pane of Thunderbird and other
XPCOM based mail cients. ...
Thunderbird extensions
rd Community / Communications Thunderbird specific : Add-ons section on developer.thunderbird.net Thunderbird communication channels Add-on Developers forum/mailing list #maildev IRC channel More general : MozillaZine Extension Development forum General developer channels Related Topics XUL, JavaScript,
XPCOM, Themes, Developing Mozilla Categori ...
libmime content type handlers
the components directory for the bin directory). Sample Content Type Handler Plugin To see an example of a Content Type Handler Plugin, the source for the handler of the content type "text/calendar" can be viewed at the following link: Calendar plugin Note: This plugin simply creates a blue table in the output stream to identify the fact that it is operational, but the basic con...
Using Mozilla code in other projects
en in Java. You can embed Gecko, the layout engine used by Firefox to process web pages, as a browser within your own application. Building XUL applications The Joy of XUL An introduction to XUL; a must read for new developers. XUL Reference The complete reference to XUL. XULRunner A Mozilla runtime package that can be used to bootstrap XUL and
XPCOM applications with ease. Mozilla Toolkit Information about the Mozilla Toolkit API. Signing Mozilla apps for Mac OS X How to code-sign applications based on Mozilla code for Mac OS X's application security model. Using Mozilla components SpiderMonkey SpiderMonkey is the JavaScript runtime engine used by Mozilla projects. NSPR The Netsc...
Debugger.Source - Firefox Developer Tools
oduced into the system; the entire string is not a valid URL. For Function.prototype's script, this is null. Source may be loaded from a URL in the following ways: The URL may appear as the src attribute of a <script> element in markup text. The URL may be passed to the Worker web worker constructor, or the web worker importScripts function. The URL may be the name of a
XPCOM JavaScript module or subscript. (Note that code passed to eval, the Function constructor, or a similar function isnot considered to be loaded from a URL; the url accessor on Debugger.Source instances for such sources should return undefined.) If the instance refers to WebAssembly code, the URL of the script that called new WebAssembly.Module with the string "> wasm" appended. sourceMa...
Debugger.Object - Firefox Developer Tools
nnotation objects have a string-valued "type" property that, taken together with the object's class, indicate what sort of thing the referent is. The host annotation object's other properties provide further details, as appropriate for the type. For example, in Firefox, a metadata object for a JavaScript Module's global object might look like this: { "type":"jsm", "uri":"resource:://gre/modules/
XPCOMUtils.jsm" } Firefox provides [DebuggerHostAnnotationsForFirefox annotations] for its host objects. Function Properties of the Debugger.Object prototype The functions described below may only be called with a this value referring to a Debugger.Object instance; they may not be used as methods of other kinds of objects. The descriptions use "referent" to mean "the referent of this Debugger.Ob...
Index - Web APIs
ne in their parent's childNodes, or returns null if the specified node is the last child in the parent element. 2723 Node.nodeName API, DOM, Gecko, NeedsSpecTable, Node, Property, Read-only The nodeName read-only property returns the name of the current Node as a string. 2724 Node.nodePrincipal API, DOM, Gecko, Node, Non-standard, Obsolete, Principal, Property,
XPCOM, nodePrincipal The Node.nodePrincipal read-only property returns the nsIPrincipal object representing current security context of the node. 2725 Node.nodeType API, DOM, Property, Reference The read-only Node.nodeType property is an integer that identifies what the node is. It distinguishes different kind of nodes from each other, such as elements, text and comments. ...
Web Storage API - Web APIs
browser crashes/restarts, the amount of data saved per origin is limited to 10MB. This has been done to avoid memory issues caused by excessive usage of web storage. Note: Access to Web Storage from third-party IFrames is denied if the user has disabled third-party cookies (Firefox implements this behaviour from version 43 onwards.) Note: Web Storage is not the same as mozStorage (Mozilla's
XPCOM interfaces to SQLite) or the Session store API (an
XPCOM storage utility for use by extensions). Web Storage interfaces Storage Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.) Window The Web Storage API extends the Window object with two new properties -- Window.sessionStorage and Window.localStorage -- which provide access to the cur...
getter - JavaScript
havior. In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value gets returned. get notifier() { delete this.notifier; return this.notifier = document.getElementById('bookmarked-notification-anchor'); }, For Firefox code, see also the
XPCOMUtils.jsm code module, which defines the defineLazyGetter() function. get vs. defineProperty While using the get keyword and Object.defineProperty() have similar results, there is a subtle difference between the two when used on classes. When using get the property will be defined on the instance's prototype, while using Object.defineProperty() the property will be defined on the instance it is...
instanceof - JavaScript
nd passing objects from one context to another via functions, this will be a valid and strong issue. For instance, you can securely check if a given object is, in fact, an Array using Array.isArray(myObj) For example, checking if a Nodes is a SVGElement in a different context, you can use myNode instanceof myNode.ownerDocument.defaultView.SVGElement. Note for Mozilla developers: In code using
XPCOM, instanceof has special effect: obj instanceof
xpcomInterface (e.g. Components.interfaces.nsIFile) calls obj.QueryInterface(
xpcomInterface) and returns true if QueryInterface succeeded. A side effect of such call is that you can use
xpcomInterface's properties on obj after a successful instanceof test. Unlike standard JavaScript globals, the test obj instanceof
xpcomInterface works as expected, ...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
Resetting The XSLTProcessor object also implements a XSLTProcessor.reset() method, which can be used to remove all stylesheets and parameters then put the processor back into its initial state. This method is implemented in Mozilla 1.3 and later. Resources The following reflect the interface of the XSLTProcessor object: nsIXSLTProcessor.idl XSLTProcessor.webidl Using XSLTProcessor from
XPCOM components Instantiating an XSLTProcessor from an
XPCOM component requires a different syntax as the constructor is not defined inside components. Instead of this: var processor = new XSLTProcessor(); Do this: var processor = Components.classes["@mozilla.org/document-transformer;1?type=xslt"] .createInstance(Components.interfaces.nsIXSLTProcessor); See also Th...