WebIDL绑定

注意:需要记录索引和命名的setter / creator / deleter的设置。

在构建时生成 WebIDL binding 需要两个东西:一个实实在在的WebIDL文件,以及另一个描述了 WebIDL 如何映射为 Gecko 内部代码的元数据配置文件。

所有的 WebIDL文件应该放置在 dom/webidl 中并将文件名添加到该目录下的 moz.build 文件的列表中。

注意如果你添加了新的接口,关于 dom/tests/mochitest/general/test_interfaces.html 很可能会失效。这就表示你需要让你的 DOM peer review 一下。不要急于在没有 review 的情况下将你的接口添加到moz.build 列表中;这样只会惹恼你的 DOM peers,最后无论如何你的改动都得被重新review。

dom/bindings/Bindings.conf配置文件是一个简单的Python dict(字典)类型数据。它会将接口名称与接口信息相映射,这被称为descriptor(python描述符)。会有各种可能的方式来处理每种边缘情况,然而大多数描述符通常都非常简单。

所有生成的代码都放置在 mozilla::dom namespace 中。对于每个接口,将创建一个名称以Binding为后缀的namespace ,与该接口的 binding 相关的所有内容都放在该namespace中。

有许多放在 dom/bindings 目录中的助手对象和工具方法同样也在 mozilla::dom 命名空间中,其头文件也被导出到了 mozilla/dom 中(在编译时会放到 $OBJDIR/dist/include 目录).。

向一个类添加 WebIDL 绑定

要将MyInterface 接口的WebIDL binding 添加到应该实现该接口的类 mozilla::dom::MyInterface中,你需要执行以下操作:

  1. 如果你的接口没有继承自其他任何接口,你应当继承 nsWrapperCache,并把该类Hook到生命周期收集器(cycle collector),以便它可以正确地跟踪 wrapper 缓存。请注意,如果您的对象只能创建,而不能从其他对象获取,则可能不需要执行此操作。如果你也继承了 nsISupports接口,请确保 nsISupports 在父类列表中位于 nsWrapperCache 之前。如果您的接口 确实 继承了别的接口,则只需继承另一个接口对应的C++类型即可。

如果确实需要Hook 生命周期收集器(cycle collector),在同样也继承了nsISupports的常见情况下,它将如下所示:

// Add strong pointers your class holds here. If you do, change to using
// NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE.
NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_0(MyClass) 
NS_IMPL_CYCLE_COLLECTING_ADDREF(MyClass)
NS_IMPL_CYCLE_COLLECTING_RELEASE(MyClass)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MyClass)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

       2. 如果你的类不是继承自实现了 GetParentObject接口的类,则添加一个同名函数。对于您的类的给定实例,该函数每次都返回相同的对象(除非您编写显式代码,通过重新设置JS wrapper来处理父对象的更改,就像节点所做的那样)。其思想是遍历 GetParentObject 链最终会将您得到 Window。这样,每个WebIDL对象都与一个特定的窗口相关联。

例如,nsINode::GetParentObject  返回节点的所有者文档。GetParentObject的返回类型并不重要,只是它必须单独从nsISupports继承,或者具有可以从中生成nsISupports的相应ToSupports方法。(这允许编译器通过该类的一个非显式构造函数将返回值隐式转换为 ParentObject实例.)

如果希望快速创建许多 MyInterface 实例,则 GetParentObject 的返回值本身应从nsWrapperCache 继承以获得最佳性能。在出于安全目的将结果对象与随机全局对象相关联的情况下,允许从GetParentObject返回null ;对于将其暴露于Web content,这通常是不合适的。同样,如果您不需要wrapper 缓存,则不需要执行此操作。从GetParentObject返回的实际类型必须在你实现的头文件中的头部 include 中导入,以便此类型的定义对绑定代码可见。

      3. 在 dom/webidl目录下添加 MyInterface 的WebIDL 定义, 并将该文件添加到 dom/webidl/moz.build 的列表中.

      4. 在dom/bindings/Bindings.conf中添加一个条目,用于设置有关接口实现的一些基本信息。如果C++类型不是 mozilla::dom::MyInterface,则需要将 'nativeType'设置为正确的类型。如果通过将“::”替换为“/”并附加“.h”路径 的该类型头文件中不存在,则将其相应的位置添加至相应的“headerFile”注释中 (或向.webidl文件添加 HeaderFile annotation 注释)。如果您不需要设置任何注释,那么您也不需要添加条目,代码生成器将简单地采用此处的默认值。请注意,通常不建议使用“headerFile”注释。如果您确实使用了它,您将需要确保您的头文件 include 了 Func 注释所需的所有头文件。

    5. 将外部接口条目添加到Bindings.conf中,用于新接口的任何 作为 非webidl接口的参数或返回值。

    6.  在mozilla::dom::MyInterface上实现WrapObject 重载,它只调用 mozilla::dom::MyInterface_Binding::Wrap。请注意,如果您的C++类型正在实现多个不同的Web IDL接口,则需要选择在此处调用哪个mozilla::dom::MyInterface_Binding::Wrap。例如,参见AudioContext::WrapObject

    7.  在mozilla::dom::MyInterface上公开接口需要的任何方法。它们可以是inline、virtual、具有任何调用约定的,等等,只要它们具有正确的参数类型和返回类型。通过运行mach webidl-example MyInterface,您可以看到函数声明应该是什么样子的示例。这将在objdir中的 dom/bindings 中生成两个文件:MyInterface-example.hMyInterface-example.cpp,这两个文件显示了使用从nsISupports继承并具有包装器缓存的类的接口的基本实现。

参见  sample patch that migrates window.performance.* to WebIDL bindings(这是一个往window添加接口的提交。译者注).

注意: 如果您的对象只能通过创建来被JS调用,而不是通过从某个地方获取它,那么您可以跳过上面的步骤1和2,而且向您的descriptor中添加 'wrapperCache': False。您需要在WebIDL中将返回对象的函数标记为[NewObject] 。如果您的对象没有使用引用计数,则返回它的函数的返回值应返回 nsAutoPtr

创建WebIDL 之  C++反射

WebIDL操作之C++反射(方法)

WebIDL操作被转换为对底层C++对象的方法调用。如何确定返回类型和参数类型的方法 如下所述。除此之外,所有 允许抛出的方法 都将获得一个附加到其参数列表中的 ErrorResult& 参数。使用特定WebIDL类型( 如 any 或者object )的非静态方法将获得参数列表之前的JSContext*参数。静态方法将被传递一个 const GlobalObject& 用作相关的全局变量,并且可以通过对其调用 Context()来获取JSContext* 。

C++方法的名称只是WebIDL操作的名称,第一个字母转换为大写。

WebIDL重载被转换为C++重载:它们只是调用具有相同名称和不同签名的C++方法。

例如如下所示的 webidl:

interface MyInterface 
{
  void doSomething(long number);
  double doSomething(MyInterface? otherInstance);

  [Throws]
  MyInterface doSomethingElse(optional long maybeNumber);
  [Throws]
  void doSomethingElse(MyInterface otherInstance);

  void doTheOther(any something);

  void doYetAnotherThing(optional boolean actuallyDoIt = false);

  static void staticOperation(any arg);
};

会需要这些方法声明:

class MyClass
{
  void DoSomething(int32_t aNumber);
  double DoSomething(MyClass* aOtherInstance);

  already_AddRefed<MyInterface> DoSomethingElse(Optional<int32_t> aMaybeNumber,
                                                ErrorResult& rv);
  void DoSomethingElse(MyClass& aOtherInstance, ErrorResult& rv);
  
  void DoTheOther(JSContext* cx, JS::Value aSomething);

  void DoYetAnotherThing(bool aActuallyDoIt);

  static void StaticOperation(const GlobalObject& aGlobal, JS::Value aSomething);
}

WebIDL属性的C++反射

WebIDL属性被转换为底层C++对象上getter和setter的一对方法调用。只读属性只有getter而没有setter。

getter的名称是将第一个字母转换为大写的属性的名称。如果满足以下任一条件,则将Get 前置:

  1. 属性的类型可以为空。
  2. getter 可以 throw。
  3. 属性的返回值通过C++ 中的 out parameter 返回。

getter的方法签名看起来就像没有参数的操作,并且属性的类型作为返回类型。

 setter 的名称是Set ,后跟属性的名称,第一个字母转换为大写。方法签名看起来就像一个具有void返回值和单个参数的操作,该参数的类型是属性的类型。

WebIDL构造函数的 C++反射

WebIDL构造函数被转换为名为Constructor的静态类方法。此方法的参数将是WebIDL构造函数的参数,带有 const GlobalObject& 用于相关的全局前缀。对于非Worker情况,全局通常是构造函数附加到的 DOM Window 的 内部 Window 。如果由于某些参数类型也需要JSContext*,则它将位于全局变量之后。MyInterface的构造函数的返回值与返回MyInterface实例的方法的返回值完全相同。始终允许构造函数 throw。

如下 IDL所示:

[Constructor,
 Constructor(unsigned long someNumber)]
interface MyInterface 
{
};

需要在 MyClass中进行如下声明:

class MyClass {
  // Various nsISupports stuff or whatnot
  static
  already_AddRefed<MyClass> Constructor(const GlobalObject& aGlobal,
                                        ErrorResult& rv);
  static
  already_AddRefed<MyClass> Constructor(const GlobalObject& aGlobal,
                                        uint32_t aSomeNumber,
                                        ErrorResult& rv);  
};

C++ reflections of WebIDL types

The exact C++ representation for WebIDL types can depend on the precise way that they're being used: e.g. return values, arguments, and sequence or dictionary members might all have different representations.

Unless stated otherwise, a type only has one representation.  Also, unless stated otherwise, nullable types are represented by wrapping Nullable<> around the base type.

In all cases, optional arguments which do not have a default value are represented by wrappingconst Optional<>& around the representation of the argument type.  If the argument type is a C++ reference, it will also become a NonNull<> around the actual type of the object in the process.  Optional arguments which do have a default value are just represented by the argument type itself, set to the default value if the argument was not in fact passed in.

Variadic WebIDL arguments are treated as a const Sequence<>& around the actual argument type.

any

any is represented in three different ways, depending on use:

  • any arguments become JS::Handle<JS::Value>.
  • any return values become a JS::MutableHandle<JS::Value> out param appended to the argument list.  This comes after all IDL arguments, but before the ErrorResult&, if any, for the method.
  • any dictionary members and sequence elements become JS::Value.  The dictionary members and sequence elements are guaranteed to be marked by whoever puts the sequence or dictionary on the stack, using SequenceRooter and DictionaryRooter.

Methods using any always get a JSContext* argument.

For example, this WebIDL:

interface Test { attribute any myAttr; any myMethod(any arg1, sequence<any> arg2, optional any arg3); };

will correspond to these C++ function declarations:

void MyAttr(JSContext* cx, JS::MutableHandle<JS::Value> retval);
void SetMyAttr(JSContext* cx, JS::Handle<JS::Value> value);
void MyMethod(JSContext* cx, JS::Handle<JS::Value> arg1, 
              const Sequence<JS::Value>& arg2,
              const Optional<JS::Handle<JS::Value> >& arg3,
              JS::MutableHandle<JS::Value> retval);

boolean

The boolean WebIDL type is represented as a C++ bool.

For example, this WebIDL:

interface Test { attribute boolean myAttr; boolean myMethod(optional boolean arg); };

will correspond to these C++ function declarations:

bool MyAttr();
void SetMyAttr(bool value);
JS::Value MyMethod(const Optional<bool>& arg);

Integer types

Integer WebIDL types are mapped to the corresponding C99 stdint types.

For example, this WebIDL:

interface Test { attribute short myAttr; long long myMethod(unsigned long? arg); };

will correspond to these C++ function declarations:

int16_t MyAttr();
void SetMyAttr(int16_t value);
int64_t MyMethod(const Nullable<uint32_t>& arg);

Floating point types

Floating point WebIDL types are mapped to the C++ type of the same name.  So float andunrestricted float become a C++ float, while double and unrestricted doublebecome a C++ double.

For example, this WebIDL:

interface Test { float myAttr; double myMethod(unrestricted double? arg); };

will correspond to these C++ function declarations:

float MyAttr();
void SetMyAttr(float value);
double MyMethod(const Nullable<double>& arg);

DOMString

Strings are reflected in three different ways, depending on use:

  • String arguments become const nsAString&.
  • String return values become a mozilla::dom::DOMString& out param appended to the argument list.  This comes after all IDL arguments, but before the ErrorResult&, if any, for the method.  Note that this allows callees to declare their methods as taking annsAString& or nsString& if desired.
  • Strings in sequences, dictionaries, owning unions, and variadic arguments becomensString.

Nullable strings are represented by the same types as non-nullable ones, but the string will return true for DOMStringIsNull().  Returning null as a string value can be done usingSetDOMStringToNull on the out param if it's an nsAString or calling SetNull() on aDOMString.

For example, this WebIDL:

interface Test { DOMString myAttr; [Throws] DOMString myMethod(sequence<DOMString> arg1, DOMString? arg2, optional DOMString arg3); };

will correspond to these C++ function declarations:

void GetMyAttr(nsString& retval);
void SetMyAttr(const nsAString& value);
void MyMethod(const Sequence<nsString>& arg1, const nsAString& arg2,
              const Optional<nsAString>& arg3, nsString& retval, ErrorResult& rv);

ByteString

ByteString is reflected in three different ways, depending on use:

  • ByteString arguments become const nsACString&.
  • ByteString return values become an nsCString& out param appended to the argument list.  This comes after all IDL arguments, but before the ErrorResult&, if any, for the method.
  • ByteString in sequences, dictionaries, owning unions, and variadic arguments becomes nsCString.

Nullable ByteString are represented by the same types as non-nullable ones, but the string will return true for IsVoid().  Returning null as a string value can be done using SetIsVoid()on the out param.

object

object is represented in three different ways, depending on use:

  • object arguments become JS::Handle<JSObject*>.
  • object return values become a JS::MutableHandle<JSObject*> out param appended to the argument list.  This comes after all IDL arguments, but before theErrorResult&, if any, for the method.
  • object dictionary members and sequence elements become JSObject*.  The dictionary members and sequence elements are guaranteed to be marked by whoever puts the sequence or dictionary on the stack, using SequenceRooter andDictionaryRooter.

Methods using object always get a JSContext* argument.

For example, this WebIDL:

interface Test { object myAttr; object myMethod(object arg1, object? arg2, sequence<object> arg3, optional object arg4, optional object? arg5); };

will correspond to these C++ function declarations:

void GetMyAttr(JSContext* cx, JS::MutableHandle<JSObject*> retval);
void SetMyAttr(JSContext* cx, JS::Handle<JSObject*> value);
void MyMethod(JSContext* cx, JS::Handle<JSObject*> arg1, JS::Handle<JSObject*> arg2,
              const Sequence<JSObject*>& arg3,
              const Optional<JS::Handle<JSObject*> >& arg4,
              const Optional<JS::Handle<JSObject*> >& arg5,
              JS::MutableHandle<JSObject*> retval);

Interface types

There are four kinds of interface types in the WebIDL bindings.  Callback interfaces are used to represent script objects that browser code can call into.  External interfaces are used to represent objects that have not been converted to the WebIDL bindings yet.  WebIDL interfaces are used to represent WebIDL binding objects.  "SpiderMonkey" interfaces are used to represent objects that are implemented natively by the JavaScript engine (e.g. typed arrays).

Callback interfaces

Callback interfaces are represented in C++ as objects inheriting frommozilla::dom::CallbackInterface, whose name, in the mozilla::dom namespace, matches the name of the callback interface in the WebIDL.  The exact representation depends on how the type is being used.

  • Nullable arguments become Foo*.
  • Non-nullable arguments become Foo&.
  • Return values become already_AddRefed<Foo> or Foo* as desired.  The pointer form is required if the method or property involved is flagged as resultNotAddRefed inBindings.conf.
  • WebIDL callback interfaces in sequences, dictionaries, owning unions, and variadic arguments are represented by nsRefPtr<Foo> if nullable and OwningNonNull<Foo>otherwise.

If the interface is a single-opertion interface, the object exposes two methods that both invoke the same underlying JS callable.  The first of these methods allows the caller to pass in a thisobject, while the second defaults to undefined as the this value.  In either case, the thisvalue is only used if the callback interface is implemented by a JS callable.  If it's implemented by an object with a property whose name matches the operation, the object itself is always used as this.

If the interface is not a single-operation interface, it just exposes a single method for every IDL method/getter/setter.

The signatures of the methods correspond to the signatures for throwing IDL methods/getters/setters with an additional trailing "mozilla::dom::CallbackObject::ExceptionHandling aExceptionHandling" argument, defaulting to eReportExceptions.  If aReportExceptions is set toeReportExceptions, the methods will report JS exceptions before returning.  IfaReportExceptions is set to eRethrowExceptions, JS exceptions will be stashed in theErrorResult and will be reported when the stack unwinds to wherever the ErrorResult was set up.

For example, this WebIDL:

callback interface MyCallback { attribute long someNumber; short someMethod(DOMString someString); }; callback interface MyOtherCallback { // single-operation interface short doSomething(Node someNode); }; interface MyInterface { attribute MyCallback foo; attribute MyCallback? bar; };

will lead to these C++ class declarations, in the mozilla::dom namespace:

class MyCallback : public CallbackInterface
{
  int32_t GetSomeNumber(ErrorResult& rv, ExceptionHandling aExceptionHandling = eReportExceptions);
  void SetSomeNumber(int32_t arg, ErrorResult& rv,
                     ExceptionHandling aExceptionHandling = eReportExceptions);
  int16_t SomeMethod(const nsAString& someString, ErrorResult& rv,
                     ExceptionHandling aExceptionHandling = eReportExceptions);
};

class MyOtherCallback : public CallbackInterface
{
public:
  int16_t
  DoSomething(nsINode& someNode, ErrorResult& rv,
              ExceptionHandling aExceptionHandling = eReportExceptions);

  template<typename T>
  int16_t
  DoSomething(const T& thisObj, nsINode& someNode, ErrorResult& rv,
              ExceptionHandling aExceptionHandling = eReportExceptions);
};

and these C++ function declarations on the implementation of MyInterface:

already_AddRefed<MyCallback> GetFoo(); void SetFoo(MyCallback&); already_AddRefed<MyCallback> GetBar(); void SetBar(MyCallback*);
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 thenativeType 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 become already_AddRefed<nsIFoo> or nsIFoo* as desired.  The pointer form is required if the method or property involved is flagged asresultNotAddRefed in Bindings.conf.
  • External interfaces in sequences, dictionaries, owning unions, and variadic arguments are represented by nsRefPtr<nsIFoo>.
WebIDL interfaces

WebIDL interfaces are represented in C++ as C++ classes.  The class involved must either be refcounted or must be explicitly annotated in Bindings.conf as being directly owned by the JS object.  If the class inherits from nsISupports, then the canonical nsISupports must be on the primary inheritance chain of the object.  If the interface has a parent interface, the C++ class corresponding to the parent must be on the primary inheritance chain of the object.  This guarantees that a void* can be stored in the JSObject which can then be reinterpret_castto any of the classes that correspond to interfaces the object implements.  The C++ type to be used should be the nativeType listed for the interface in the Bindings.conf file, ormozilla::dom::InterfaceName if none is listed.  The exact representation depends on how the type is being used.

  • Nullable arguments become Foo*.
  • Non-nullable arguments become Foo&.
  • Return values become already_AddRefed<Foo> or Foo* as desired.  The pointer form is required if the method or property involved is flagged as resultNotAddRefed inBindings.conf.
  • WebIDL interfaces in sequences, dictionaries, owning unions, and variadic arguments are represented by nsRefPtr<Foo> if nullable and OwningNonNull<Foo> otherwise.

For example, this WebIDL:

interface MyInterface { attribute MyInterface myAttr; void passNullable(MyInterface? arg); MyInterface? doSomething(sequence<MyInterface> arg); MyInterface doTheOther(sequence<MyInterface?> arg); readonly attribute MyInterface? nullableAttr; readonly attribute MyInterface someOtherAttr; // Marked as resultNotAddRefed readonly attribute MyInterface someYetOtherAttr; };

Would correspond to these C++ function declarations:

already_AddRefed<MyClass> MyAttr();
void SetMyAttr(MyClass& value);
void PassNullable(MyClass* arg);
already_AddRefed<MyClass> doSomething(const Sequence<OwningNonNull<MyClass> >& arg);
already_AddRefed<MyClass> doTheOther(const Sequence<nsRefPtr<MyClass> >& arg);
already_Addrefed<MyClass> GetMyAttr();
MyClass* SomeOtherAttr();
MyClass* SomeYetOtherAttr(); // Don't have to return already_AddRefed!
"SpiderMonkey" interfaces

Typed array, array buffer, and array buffer view arguments are represented by the objects inTypedArray.h.  For example, this WebIDL:

interface Test { void passTypedArrayBuffer(ArrayBuffer arg); void passTypedArray(ArrayBufferView arg); void passInt16Array(Int16Array? arg); }

will correspond to these C++ function declarations:

void PassTypedArrayBuffer(const ArrayBuffer& arg);
void PassTypedArray(const ArrayBufferView& arg);
void PassInt16Array(const Nullable<Int16Array>& arg);

Typed array return values are represented by JSObject*.

Typed arrays store a JSObject* and hence need to be rooted properly.  On-stack typed arrays can be declared as RootedTypedArray<TypedArrayType> (e.g.RootedTypedArray<Int16Array>).  Typed arrays on the heap need to be traced.

Dictionary types

A dictionary argument is represented by a const reference to a struct whose name is the dictionary name in the mozilla::dom namespace.  The struct has one member for each of the dictionary's members with the same name except the first letter uppercased and prefixed with "m". The members that have default values have types as described under the corresponding WebIDL type in this document.  The members that don't have default values have those types wrapped in Optional<>.

Dictionary return values are represented by an out parameter whose type is a non-const reference to the struct described above, with all the members that have default values preinitialized to those default values.

Note that optional dictionary arguments are always considered to have a default value of nullso dictionary arguments are never wrapped in Optional<>.

If necessary, dictionaries can be directly initialized from a JS::Value in C++ code by invoking their Init() method.  Consumers doing this should declare their dictionary asRootedDictionary<DictionaryName>.  When this is done, passing in a null scope object and even a null JSContext* is allowed if the passed-in JS::Value is JS::NullValue().  Likewise, a dictionary struct can be converted to a JS::Value in C++ by calling ToJSValuewith the dictionary as the second argument.  If Init() or ToJSValue() return false, they will generally set a pending exception on the JSContext; reporting those is the responsibility of the caller.

For example, this WebIDL:

dictionary Dict { long foo = 5; DOMString bar; }; interface Test { void initSomething(optional Dict arg); };

will correspond to this C++ function declaration:

void InitSomething(const Dict& arg);

and the Dict struct will look like this:

struct Dict {
  bool Init(JSContext* aCx, JS::Handle<JS::Value> aVal, const char* aSourceDescription = "value");

  Optional<nsString> mBar;
  int32_t mFoo;
}

Note that the dictionary members are sorted in the struct in alphabetical order.

Enumeration types

WebIDL enumeration types are represented as C++ enums.  The values of the C++ enum are named by taking the strings in the WebIDL enumeration, replacing all non-alphanumerics with underscores, and uppercasing the first letter, with a special case for the empty string, which becomes the value _empty.

For a WebIDL enum named MyEnum, the C++ enum is named MyEnum and placed in themozilla::dom namespace, while the values are placed in the mozilla::dom::MyEnumnamespace.  There is also a mozilla::dom::MyEnumValues::strings which is an array ofmozilla::dom::EnumEntry structs that gives access to the string representations of the values.

For example, this WebIDL:

enum MyEnum { "something", "something-else", "", "another" };

would lead to this C++ enum declaration:

MOZ_BEGIN_ENUM_CLASS(MyEnum, uint32_t)
  Something,
  Something_else,
  _empty,
  Another
MOZ_END_ENUM_CLASS(MyEnum)

namespace MyEnumValues {
extern const EnumEntry strings[10];
} // namespace MyEnumValues

Callback function types

Callback functions are represented as an object, inheriting frommozilla::dom::CallbackFunction, whose name, in the mozilla::dom namespace, matches the name of the callback function in the WebIDL.  If the type is nullable, a pointer is passed in; otherwise a reference is passed in.

The object exposes two Call methods, which both invoke the underlying JS callable.  The firstCall method has the same signature as a throwing method declared just like the callback function, with an additional trailing "mozilla::dom::CallbackObject::ExceptionHandling aExceptionHandling" argument, defaulting to eReportExceptions, and calling it will invoke the callable withundefined as the this value.  The second Call method allows passing in an explicit thisvalue as the first argument.  This second call method is a template on the type of the first argument, so the this value can be passed in in whatever form is most convenient, as long as it's either a type that can be wrapped by XPConnect or a WebIDL interface type.

If aReportExceptions is set to eReportExceptions, the Call methods will report JS exceptions before returning.  If aReportExceptions is set to eRethrowExceptions, JS exceptions will be stashed in the ErrorResult and will be reported when the stack unwinds to wherever the ErrorResult was set up.

For example, this WebIDL:

callback MyCallback = long (MyInterface arg1, boolean arg2); interface MyInterface { attribute MyCallback foo; attribute MyCallback? bar; };

will lead to this C++ class declaration, in the mozilla::dom namespace:

class MyCallback : public CallbackFunction
{
public:
  int32_t
  Call(MyInterface& arg1, bool arg2, ErrorResult& rv,
       ExceptionHandling aExceptionHandling = eReportExceptions);

  template<typename T>
  int32_t
  Call(const T& thisObj, MyInterface& arg1, bool arg2, ErrorResult& rv,
       ExceptionHandling aExceptionHandling = eReportExceptions);
};

and these C++ function declarations in the MyInterface class:

already_AddRefed<MyCallback> GetFoo(); void SetFoo(MyCallback&); already_AddRefed<MyCallback> GetBar(); void SetBar(MyCallback*);

Sequences

Sequence arguments are represented by const Sequence<T>&, where T depends on the type of elements in the WebIDL sequence.

Sequence return values are represented by an nsTArray<T> out param appended to the argument list, where T is the return type for the elements of the WebIDL sequence.  This comes after all IDL arguments, but before the ErrorResult&, if any, for the method.

Arrays

IDL array objects are not supported yet.  The spec on these is likely to change drastically anyway.

Union types

Union types are reflected as a struct in the mozilla::dom namespace.  There are two kinds of union structs: one kind does not keep its members alive (is "non-owning"), and the other does (is "owning").  Const references to non-owning unions are used for plain arguments.  Owning unions are used in dictionaries, sequences, and for variadic arguments.  Union return values become a non-const owning union out param.  The name of the struct is the concatenation of the names of the types in the union, with "Or" inserted between them, and for an owning struct "Owning" prepended.  So for example, this IDL:

void passUnion((object or long) arg); (object or long) receiveUnion(); void passSequenceOfUnions(sequence<(object or long)> arg); void passOtherUnion((HTMLDivElement or ArrayBuffer or EventInit) arg);

would correspond to these C++ function declarations:

void PassUnion(const ObjectOrLong& aArg);
void ReceiveUnion(OwningObjectObjectOrLong& aArg);
void PassSequenceOfUnions(const Sequence<OwningObjectOrLong>& aArg);
void PassOtherUnion(const HTMLDivElementOrArrayBufferOrEventInit& aArg);

Union structs expose accessors to test whether they're of a given type and to get hold of the data of that type.  They also expose setters that set the union as being of a particular type and return a reference to the union's internal storage where that type could be stored.  The one exception is the object type, which uses a somewhat different form of setter where theJSObject* is passed in directly. For example, ObjectOrLong would have the following methods:

bool IsObject() const;
JSObject* GetAsObject() const;
void SetToObject(JSContext*, JSObject*);
bool IsLong() const;
int32_t GetAsLong() const;
int32_t& SetAsLong()

Owning unions used on the stack should be declared as a RootedUnion<UnionType>.  For example, RootedUnion<OwningObjectOrLong>.

Date

WebIDL Date types are represented by a mozilla::dom::Date struct.

Stringifiers

Named stringifiers operations in WebIDL will just invoke the corresponding C++ method.

Anonymous stringifiers in WebIDL will invoke the C++ method called Stringify.  So for example given this IDL:

interface FirstInterface { stringifier; }; interface SecondInterface { stringifier DOMString getStringRepresentation(); };

the corresponding C++ would be:

class FirstInterface { public: void Stringify(nsAString& aResult); }; class SecondInterface { public: void GetStringRepresentation(nsAString& aResult); };

Legacy Callers

Only anonymous legacy callers are supported, and will invoke the C++ method calledLegacyCall.  This will be passed the JS "this" value as the first argument, then the arguments to the actual operation.  A JSContext will be passed if any of the operation arguments need it.  So for example given this IDL:

interface InterfaceWithCall { legacycaller long (float arg); };

the corresponding C++ would be:

class InterfaceWithCall {
public:
  int32_t LegacyCall(JS::Handle<JS::Value> aThisVal, float aArgument);
};

Named getters

If the interface has a named getter, the binding will expect several methods on the C++ implementation:

  • NamedGetter method.  This takes a property name and returns whatever type the named getter is declared to return.  It also has a boolean out param for whether a property with that name should exist at all.
  •  A NameIsEnumerable method.  This takes a  that takes a property name and returns a boolean that indicates whether the property is enumerable.
  • GetSupportedNames method.  This takes an unsigned integer which corresponds to the flags passed to the iterate proxy trap and returns a list of property names.  For implementations of this method, the important flags is JSITER_HIDDEN.  If that flag is set, the call needs to return all supported property names.  If it's not set, the call needs to return only the enumerable ones.

The NameIsEnumerable and GetSupportedNames methods need to agree on which names are and are not enumerable.  The NamedGetter and GetSupportedNames methods need to agree on which names are supported.

So for example, given this IDL:

interface InterfaceWithNamedGetter { getter long(DOMString arg); };

the corresponding C++ would be:

class InterfaceWithNamedGetter 
{
public:
  int32_t NamedGetter(const nsAString& aName, bool& aFound);
  bool NameIsEnumerable(const nsAString& aName);
  void GetSupportedNames(unsigned aFlags, nsTArray<nsString>& aNames);
};

Throwing exceptions from WebIDL methods, getters, and setters

WebIDL methods, getters, and setters that are explicitly marked as allowed to throw have anErrorResult& argument as their last argument.  To throw an exception, simply call Throw()on the ErrorResult& and return from your C++ back into the binding code.

In cases when the specification calls for throwing a TypeError, you should useErrorResult::ThrowTypeError() instead of calling Throw().

Custom extended attributes

Our WebIDL parser and code generator recognize several extended attributes that are not present in the WebIDL spec.

[ChromeOnly]

This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole.

Interface members flagged as [ChromeOnly] are only exposed in chrome Windows (and in particular, are not exposed to webpages).  From the point of view of web content, it's as if the interface member were not there at all.  These members are exposed to chrome script working with a content object via Xrays.

If specified on an interface as a whole, this functions like [Func] except that the binding code will automatically check whether the caller script has the system principal (is chrome or a worker started from a chrome page) instead of calling into the C++ implementation to determine whether to expose the interface object on the global.   This means that accessing a  content global via Xrays will show [ChromeOnly] interface objects on it.

This extended attibute can be specified together with [AvailableIn][CheckPermissions],[Func],  and [Pref].  If more than one of these is specified, all conditions will need to test true for the interface or interface member to be exposed.

[Pref=prefname]

This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole. It takes a value, which must be the name of a boolean preference.

If specified on an interface member, the interface member involved is only exposed if the preference is set to true. An example of how this can be used:

interface MyInterface { attribute long alwaysHere; [Pref="my.pref.name"] attribute long onlyHereIfEnabled; };

If specifed on an interface as a whole, this functions like [Func] except that the binding will check the value of the preference directly without calling into the C++ implementation of the interface at all. This is useful when the enable check is simple and it's desirable to keep the prefname with the WebIDL declaration. The implementation can callMyInterfaceBinding::PrefEnabled() to check whether it is enabled or not.  An example of how this can be used:

[Pref="my.pref.name"] interface MyConditionalInterface { };

This extended attibute can be specified together with [AvailableIn][CheckPermissions],[ChromeOnly], and[Func].  If more than one of these is specified, all conditions will need to test true for the interface or interface member to be exposed.

[Func="funcname"]

This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole.  It takes a value, which must be the name of a static function. 

If specified on an interface member, the interface member involved is only exposed if the specified function returns true.   An example of how this can be used:

interface MyInterface { attribute long alwaysHere; [Func="MyClass::StuffEnabled"] attribute long onlyHereIfEnabled; };

The function is invoked with two arguments: the JSContext that the operation is happening on and the JSObject for the global of the object that the property will be defined on if the function returns true.  In particular, in the Xray case the JSContext is in the caller compartment (typically chrome) but the JSObject is in the target compartment (typically content).  This allows the method implementation to select which compartment it cares about in its checks.

The above IDL would also require the following C++:

class MyClass {
  static bool StuffEnabled(JSContext* cx, JSObject* obj);
};

If specified on an interface as a whole, then lookups for the interface object for this interface on a DOM Window will only find it if the specified function returns true.  For objects that can only be created via a constructor, this allows disabling the functionality altogether and making it look like the feature is not implemented at all.

An example of how [Func] can be used:

[Func="MyClass::MyConditionalInterfaceEnabled"] interface MyConditionalInterface { };

In this case, the C++ function is passed a JS::Handle<JSObject*>.  So the C++ in this case would look like this:

class MyClass {
  static bool MyConditionalInterfaceEnabled(JSContext* cx, JS::Handle<JSObject*> obj);
};

Just like in the interface member case, the JSContext is in the caller compartment but theJSObject is the actual object the property would be defined on.  In the Xray case that mean obj is in the target compartment (typically content) and cx is typically chrome.

This extended attibute can be specified together with [AvailableIn][CheckPermissions],[ChromeOnly], and [Pref].  If more than one of these is specified, all conditions will need to test true for the interface or interface member to be exposed.

[AvailableIn=Where]

This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole. It takes a value, which must be either PrivilegedApps orCertifiedApps.  This will make the interface or interface member only visible in privileged and certified apps respectively on Firefox OS.

This extended attibute can be specified together with [ChromeOnly][CheckPermissions],[Func], and  [Pref].  If more than one of these is specified, all conditions will need to test true for the interface or interface member to be exposed.

[CheckPermissions="list of permissions"]

This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole. It takes a whitespace-separated list of permissions to be checked before making the interface or interface member visible to a page or app. When multiple permission names are specified, at least one of them will need to be set to nsIPermissionManager::ALLOW_ACTION for the interface or interface member to be exposed.

This extended attribute can be specified together with [AvailableIn][ChromeOnly],[Func] and [Pref]. If more than one of these is specified, all conditions will need to test true for the interface or interface member to be exposed.

[Throws][GetterThrows][SetterThrows]

Used to flag methods or attributes as allowing the C++ callee to throw.  This causes the binding generator, and in many cases the JIT, to generate extra code to handle possible exceptions.  Possibly-throwing methods and attributes get an ErrorResult& argument.

[Throws] applies to both methods and attributes; for attributes it means both the getter and the setter can throw.  [GetterThrows] applies only to attributes.  [SetterThrows] applies only to non-readonly attributes.

For bindings that involve workers, the above can all be specified with MainThread or Workersas a value.  When doing this, if [Throws] is specified on an attribute, no matter what its value, then [GetterThrows] and [SetterThrows] will be ignored.  So to have an attribute which can throw both when getting and setting on main thread but can only throw from the setter in workers, use [SetterThrows, GetterThrows=MainThread].

For interfaces flagged with [JSImplementation], all methods and properties are assumed to be able to throw and do not need to be flagged as throwing.

[Pure]

Used to flag attributes whose getter has no side-effects or methods that have no side-effects in the DOM.  Attributes/methods flagged in this way promise that they will keep returning the same value as long as no DOM setters or non-[Pure] DOM methods executed.  This allows the JIT to perform loop-hoisting and common subexpression elimination on the return values of these attributes/methods in some cases.  [Pure] things are allowed to throw exceptions as long as they do so deterministically.  This extended attribute can be used on writable attributes as long as the getter obeys the above rules.

[Constant]

Used to flag readonly attributes that could have been annotated with [Pure] and also always return the same value.  This allows the JIT to do even more aggressive optimization of getters for such attributes.  This should only be used when it's absolutely guaranteed that the return value of the attribute getter will always be the same from the JS engine's point of view.  This extended attribute implies [Pure] as far as the JIT is concerned.

[NeedNewResolve]

Used to flag interfaces which have a custom resolve hook.  This annotation will cause theDoNewResolve method to be called on the underlying C++ class when a property lookup happens on the object.  The signature of this method is: bool DoNewResolve(JSContext*, JS::Handle<JSObject*>, JS::Handle<jsid>, JS::MutableHandle<JS::Value>).  Here the passed-in object is the object the property lookup is happening on (which may be an Xray for the actual DOM object) and the jsid is the property name.  The value that the property should have is returned in the MutableHandle<Value>, with UndefinedValue() indicating that the property does not exist.

If this extended attribute is used, then the underlying C++ class must also implement a method called GetOwnPropertyNames with the signature void GetOwnPropertyNames(JSContext* aCx, nsTArray<nsString>& aNames, ErrorResult& aRv).  This method wil be called by the JS engine's enumerate hook and must provide a superset of all the property names that DoNewResolve might resolve.  Providing names that DoNewResolve won't actually resolve is OK.

[HeaderFile="path/to/headerfile.h"]

Indicates where the implementation can be found. Similar to the headerFile annotation in Bindings.conf.

[JSImplementation="@mozilla.org/some-contractid;1"]

Used on an interface to provide the contractid of the JavaScript component implementing the interface.

Setting this extended attribute to propName on an interface causeswindow.navigator.propName to be an instance of the interface.

[StoreInSlot]

Used to flag attributes that can be gotten very quickly from the JS object by the JIT.  Such attributes will have their getter called immediately when the JS wrapper for the DOM object is created, and the returned value will be stored directly on the JS object.  Later gets of the attribute will not call the C++ getter and instead use the cached value.  If the value returned by the attribute needs to change, the C++ code should call the ClearCachedFooValue method in the namespace of the relevant binding, where foo is the name of the attribute.  This will immediately call the C++ getter and cache the value it returns, so it needs a JSContext to work on.  This extended attribute can only be used in on attributes whose getters are [Pure] or[Constant] and which are not [Throws] or [GetterThrows].

So for example, given this IDL:

interface MyInterface { [Pure, StoreInSlot] attribute long myAttribute; };

the C++ implementation of MyInterface would clear the cached value by callingmozilla::dom::MyInterfaceBinding::ClearCachedMyAttributeValue(cx, this).

If the attribute is not readonly, setting it will automatically clear the cached value and reget it again before the setter returns.

[Cached]

Used to flag attributes that, when their getter is called, will cache the returned value on the JS object.  This can be used to implement attributes whose value is a sequence or dictionary (which would otherwise end up returning a new object each time and hence not be allowed in WebIDL).

Unlike [StoreInSlot] this does not cause the getter to be eagerly called at JS wrapper creation time; the caching is lazy.  [Cached] attributes must be [Pure] or [Constant], because otherwise not calling the C++ getter would be observable, but are allowed to have throwing getters.  Their cached value can be cleared by calling the ClearCachedFooValue method in the namespace of the relevant binding, where foo is the name of the attribute.  Unlike [StoreInSlot] attributes, doing so will not immediately invoke the getter, so does not need a JSContext.

So for example, given this IDL:

interface MyInterface { [Pure, StoreInSlot] attribute long myAttribute; };

the C++ implementation of MyInterface would clear the cached value by callingmozilla::dom::MyInterfaceBinding::ClearCachedMyAttributeValue(this).

If the attribute is not readonly, setting it will automatically clear the cached value.

[Frozen]

Used to flag attributes that, when their getter is called, will call Object.freeze on the return value before returning it.  This extended attribute is only allowed on attributes that return sequences, and corresponds to returning a frozen Array.

[ChromeConstructor]

[ChromeConstructor] has the same behaviour as [Constructor], but the constructor will throw if it's not called from chrome code. The usage rules and restrictions as those for[Constructor] apply. Note that [Constructor] and [ChromeConstructor] are mutually exclusive, while there can be multiple of either, there can never be both on the same interface.

Helper objects

The C++ side of the bindings uses a number of helper objects.

Nullable<T>

Nullable<> is a struct declared in Nullable.h and exported tomozilla/dom/Nullable.h that is used to represent nullable values of types that don't have a natural way to represent null.

Nullable<T> has an IsNull() getter that returns whether null is represented and a Value()getter that returns a const T& and can be used to get the value when it's not null.

Nullable<T> has a SetNull() setter that sets it as representing null and two setters that can be used to set it to a value: "void SetValue(T)" (for setting it to a given value) and "T& SetValue()" for directly modifying the underlying T&.

Optional<T>

Optional<> is a struct declared in BindingDeclarations.h and exported tomozilla/dom/BindingDeclarations.h that is used to represent optional arguments and dictionary members, but only those that have no default value.

Optional<T> has a WasPassed() getter that returns true if a value is available.  In that case, the Value() getter can be used to get a const T& for the value.

NonNull<T>

NonNull<T> is a struct declared in BindingUtils.h and exported tomozilla/dom/BindingUtils.h that is used to represent non-null C++ objects.  It has a conversion operator that produces T&.

OwningNonNull<T>

OwningNonNull<T> is a struct declared in BindingUtils.h and exported tomozilla/dom/BindingUtils.h that is used to represent non-null C++ objects and holds a strong reference to them.  It has a conversion operator that produces T&.

Typed arrays, arraybuffers, array buffer views

TypedArray.h is exported to mozilla/dom/TypedArray.h and exposes structs that correspond to the various typed array types, as well as ArrayBuffer and ArrayBufferView, all in the mozilla::dom namespace.  Each struct has an Data() method that returns a pointer to the relevant type (uint8_t for ArrayBuffer and ArrayBufferView) and a Length()method that returns the length in units of *Data().  So for example, Int32Array has aData() returning int32_t* and a Length() that returns the number of 32-bit ints in the array..

Sequence<T>

Sequence<> is a type declared in BindingDeclarations.h and exported tomozilla/dom/BindingDeclarations.h that is used to represent sequence arguments.  It's some kind of typed array, but which exact kind is opaque to consumers.  This allows the binding code to change the exact definition (e.g. to use auto arrays of different sizes and so forth) without having to update all the callees.

CallbackFunction

CallbackFunction is a type declared in CallbackFunction.h and exported tomozilla/dom/CallbackFunction.h that is used as a common base class for all the generated callback function representations.  This class inherits from nsISupports, and consumers must make sure to cycle-collect it, since it keeps JS objects alive.

CallbackInterface

CallbackInterface is a type declared in CallbackInterface.h and exported tomozilla/dom/CallbackInterface.h that is used as a common base class for all the generated callback interface representations.  This class inherits from nsISupports, and consumers must make sure to cycle-collect it, since it keeps JS objects alive.

DOMString

DOMString is a class declared in BindingDeclarations.h and exported tomozilla/dom/BindingDeclarations.h that is used for WebIDL DOMString return values.  It has a conversion operator to nsString& so that it can be passed to methods that take that type or nsAString&, but callees that care about performance, have an nsStringBufferavailable, and promise to hold on to the nsStringBuffer at least until the binding code comes off the stack can also take a DOMString directly for their string return value and call itsSetStringBuffer method with the nsStringBuffer and its length.  This allows the binding code to avoid extra reference-counting of the string buffer in many cases, and allows it to take a faster codepath even if it does end up having to addref the nsStringBuffer.

GlobalObject

GlobalObject is a class declared in BindingDeclarations.h and exported tomozilla/dom/BindingDeclarations.h that is used to represent the global object for static attributes and operations (including constructors).  It has a Get() method that returns theJSObject*  for the global and a GetAsSupports() method that returns an nsISupports*for the global on the main thread, if such is available. It also has a GetContext() method that returns the JSContext* the call is happening on.  A caveat: the compartment of theJSContext may not match the compartment of the global!

Date

Date is a class declared in BindingDeclarations.h and exported tomozilla/dom/BindingDeclarations.h that is used to represent WebIDL Dates.  It has aTimeStamp() method returning a double which represents a number of milliseconds since the epoch, as well as SetTimeStamp() methods that can be used to initialize it with a double timestamp or a JS Date object.  It also has a ToDateObject() method that can be used to create a new JS Date.

ErrorResult

ErrorResult is a class declared in ErrorResult.h and exported to mozilla/ErrorResult.hthat is used to represent exceptions in WebIDL bindings.  This has the following methods:

  • Throw: allows throwing an nsresult.  The nsresult must be a failure code.
  • ThrowTypeError: allows throwing a TypeError with the given error message.  The list of allowed TypeErrors and corresponding messages is indom/bindings/Errors.msg.
  • ThrowJSException: allows throwing a preexisting JS exception value. However, theMightThrowJSException() method must be called before any such exceptions are thrown (even if no exception is thrown).
  • Failed: checks whether an exception has been thrown on this ErrorResult.
  • ErrorCode: returns a failure nsresult representing (perhaps incompletely) the state of this ErrorResult.
  • operator=: takes an nsresult and acts like Throw if the result is an error code, and like a no-op otherwise (unless an exception has already been thrown, in which case it asserts).  This should only be used for legacy code that has nsresult everywhere; we would like to get rid of this operator at some point.

Bindings.conf details

XXXbz write me.  In particular, need to describe at least use of concreteprefable, andaddExternalInterface

How to get a JSContext passed to a given method

In some rare cases you may need a JSContext* argument to be passed to a C++ method that wouldn't otherwise get such an argument. To see how to achieve this, search forimplicitJSContext in dom/bindings/Bindings.conf.

Implementing WebIDL using Javascript

There is support for implementing WebIDL interfaces in JavaScript.  When this is done, there are actually two objects created: the implementation object (running as a chrome-privileged script) and the content-exposed object (which is what the web page sees).  This allows the implementation object to have various APIs that the content-exposed object does not.  It also means that consumers have to be careful about which object they are creating.

Creating JS-implemented WebIDL objects

To create a JS-implemented WebIDL object, one must create both the chrome-side implementation object and the content-side page-exposed object. There are three ways to do this.

Using the WebIDL constructor

If the interface has a constructor, a content-side object can be created by getting that constructor from the relevant content window and invoking it. For example:

var contentObject = new contentWin.RTCPeerConnection();

The returned object will be an Xray wrapper for the content-side object. Creating the object this way will automatically create the chrome-side object using its contractID.

This method is limited to the constructor signatures exposed to webpages. Any additional configuration of the object needs to be done via [ChromeOnly] methods on the interface. 

Creating many objects this way can be slow due to the createInstance overhead involved. 

Using a _create method  

 A content-side object can be created for a given chrome-side object by invoking the static_create method on the interface. This method takes two arguments: the content window in which to create the object and the chrome-side object to use. For example:

var contentObject = RTCPeerConnection._create(contentWin,
                                              new MyPeerConnectionImpl());

However, if you are in a JS component, you may only be able to get to the correct interface object via some window object. In this case, the code would look more like:

var contentObject = contentWin.RTCPeerConnection._create(contentWin,
                                                         new MyPeerConnectionImpl());

Creating the object this way will not invoke its __init method or init method.

By returning a chrome-side object from a JS-implemented WebIDL method

If a JS-implemented WebIDL method is declared as returning a JS-implemented interface, then a non-WebIDL object returned from that method will be treated as the chrome-side part of a JS-implemented WebIdL object and the content-side part will be automatically created.

Creating the object 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.  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 directions for how to do this can be found elsewhere on MDN.  Use the same contract ID as you specified in the WebIDL file.  The class ID doesn't matter, except that it should be a newly generated one.  ForQueryInterface, you only need to implement nsISupports, not anything corresponding to the WebIDL interface.  The name you use for the XPCOM component should be distinct from the name of the interface, to avoid confusing error messages.

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.  Note that any other instances of the interface that you are passed in as arguments are the full web-facing version of the object, and not the JS implementation, so you currently cannot access any private data.

The WebIDL constructor invocation will first create your object.  If the XPCOM component implements nsIDOMGlobalPropertyInitializer, then the object's init method will be invoked with a single argument: the content window the constructor came from.  This allows the JS implementation to know which content window it's associated with.  The init method should not return anything.  After this, the content-side object will be created. Then, if there are any constructor arguments, the object's __init method will be invoked, with the constructor arguments as its arguments.

If you want an instance of the class to be added to window.navigator, add an extended attribute NavigatorProperty="PropertyName" which will make the instance available aswindow.navigator.PropertyName.

Checking for Permissions or Preferences

When implementing an XPIDL interface using Javascript, the init method may check if the caller has the proper permissions, or if the appropriate preference is set. If this check fails, then it will return null to indicate that the object should not be created.  JS-implemented WebIDL does NOT work like that.  In JS-implemented WebIDL, the init method should only return undefined.  If any other value, such as null, is returned, the bindings code will assert or crash.  In other words, it acts like it has a "void" return type.

Instead, preference or permission checking should be implemented by adding an extended attribute to the WebIDL interface. This has the advantage that if the check fails, the constructor or object will not show up at all.

For preference checking, add an extended attribute Pref="myPref.enabled" wheremyPref.enabled is the preference that should be checked.  SettingsLock is an example of this.

For permissions or other kinds of checking, add an extended attributeFunc="MyPermissionChecker" where MyPermissionChecker is a function implemented in C++ that returns true if the interface should be enabled.  This function can do whatever checking is needed.  One example of this is PushManager.

Example

Here's an example JS implementation of the above interface. The invisibleValue field will not be accessible to web content, but is usable by the doNothing() method.

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); function MyNumberInner() { this.value = 111; this.invisibleValue = 12345; } MyNumberInner.prototype = { classDescription: "Get my number XPCOM Component", classID: Components.ID("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"), // dummy UUID contractID: "@mozilla.org/my-number;1", QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsISupports]), doNothing: function() {}, get otherValue() { return this.invisibleValue - 4; }, __init: function(firstNumber) { if (arguments.length > 0) { this.value = firstNumber; } } } var components = [MyNumberInner]; var NSGetFactory = XPCOMUtils.generateNSGetFactory(components);

Finally, add a component and a contract and whatever other manifest stuff you need to implement an XPCOM component.

Guarantees provided by bindings

When implementing a WebIDL interface in JavaScript, certain guarantees will be provided by the binding implementation.  For example, string or numeric arguments will actually be primitive strings or numbers.  Dictionaries will contain only the properties that they are declared to have, and they will have the right types.  Interface arguments will actually be objects implementing that interface.

What the bindings will NOT guarantee is much of anything about object and any arguments.  They will get cross-compartment wrappers that make touching them from chrome code not be an immediate security bug, but otherwise they can have quite surprising behavior if the page is trying to be malicious.  Try to avoid using these types if possible.

Accessing the content object from the implementation

If the JS implementation of the WebIDL interface needs to access the content object, it is available as a property called __DOM_IMPL__ on the chrome implementation object.  This property only appears after the content-side object has been created. So it is available in__init but not in init.

Determining the principal of the caller that invoked the WebIDL API

This can be done by calling Component.utils.getWebIDLCallerPrincipal().

Throwing exceptions from JS-implemented APIs

There are two reasons a JS implemented API might throw.  The first reason is that some unforeseen condition occurred and the second is that a specification requires an exception to be thrown.

When throwing for an unforeseen condition, the exception will be reported to the console, and a sanitized NS_ERROR_UNEXPECTED exception will be thrown to the calling content script, with the file/line of the content code that invoked your API.  This will avoid exposing chrome URIs and other implementation details to the content code.

When throwing because a specification requires an exception, you need to communicate to the binding code that this is what you're doing.  Right now this is done by throwing a DOMErrorfrom the window your WebIDL object is associated with (the one that was passed to your initmethod).  The binding code will then rethrow just the message string of that DOMError to the web page, as a plain JS Error.  This does not allow implementing exceptions per spec (e.g. there is no way to explicitly throw a TypeError or other Error subclass), unfortunately; we're still working on that.  Since you know for this case the exception is being thrown because a spec requires it, you know you need to create the DOMError.  An example of how this could work:

if (!isValid(passedInObject)) {
  throw new this.contentWindow.DOMError("Error", "Object is invalid");
}

In some cases you may need to perform operations whose exception message you just want to propagate to the content caller.  This can be done like so:

try {
  someOperationThatCanThrow();
} catch (e) {
  throw new this.contentWindow.DOMError(e.name, e.message);
}

Inheriting from interfaces implemented in C++

It's possible to have an interface implemented in JavaScript inherit from an interface implemented in C++.  To do so, simply have one interface inherit from the other and the bindings code will auto-generate a C++ object inheriting from the implementation of the parent interface.  The class implementing the parent interface will need a constructor that takes annsPIDOMWindow* (though it doesn't have to do anything with that argument).

If the class implementing the parent interface is abstract and you want to use a specific concrete class as the implementation to inherit from, you will need to add a defaultImpl annotation to the descriptor for the parent interface in Bindings.conf.  The value of the annotation is the C++ class to use as the parent for JS-implemented descendants; if defaultImpl is not specified, the nativeType will be used.

For example, consider this interface that we wish to implement in JavaScript:

[JSImplementation

="some-contract"] interface MyEventTarget : EventTarget { attribute EventHandler onmyevent; void dispatchTheEvent(); // Sends a "myevent" event to this EventTarget }

The implementation would look something like this, ignoring the XPCOM boilerplate:

function MyEventTargetImpl() { } MyEventTargetImpl.prototype = { init: function(contentWindow) { // XXXbz need to document how to get this called on you! this.contentWindow = contentWindow; } get onmyevent() { return this.__DOM_IMPL__.getEventHandler("onmyevent"); } set onmyevent(handler) { this.__DOM_IMPL__.setEventHandler("onmyevent", handler); } dispatchTheEvent: function() { var event = new this.contentWindow.Event("myevent"); this.__DOM_IMPL__.dispatchEvent(event); } };

The implementation would automatically support the API exposed on EventTarget (so for example addEventListener).  Calling the dispatchTheEvent method would cause dispatch of an event that content script can see via listeners it has added.

Note that in this case the chrome implementation is relying on some [ChromeOnly] methods on EventTarget that were added specifically to make it possible to easily implement event handlers.  Other cases can do similar things as needed