是时候了解一下 Web IDL

吴小倩, W3C
2019年 11 月


是时候了解一下 Web IDL

吴小倩, W3C
2019年 11 月

W3C logo

Web IDL 是指?

Web IDL in 2019

2019 的 Web

Various technologies expanding the Web Core capabilities

WebIDL for APIs

[SecureContext, Exposed=Window]
interface PaymentRequest : EventTarget {
  constructor(
    sequence<PaymentMethodData> methodData,
    PaymentDetailsInit details,
    optional PaymentOptions options = {}
  );
  [NewObject]
  Promise<PaymentResponse> show(optional Promise<PaymentDetailsUpdate> detailsPromise);
  readonly attribute DOMString? shippingOption;
}

Web 需要 Web IDL

Web IDL 的关键在于定义了如何把 DOM 和相关的 Web API 映射到语言里,尤其是 ECMAScript。之前的标准都使用 OMG IDL,没有正式的对这些映射关系做出定义,实现者需要从字里行间猜测。
Maciej Stachowiak (Webkit), 2009-9-28

Platform objects?
Yes! Yes! Yes! Yes!

Web 需要 Web IDL

Platform objects?
Yes! Yes! Yes! Yes!

我们需要 Web IDL 吗?

  • 读懂 DOM 和 Web API 定义
  • 更好地书写你对 Web 的想法提案
  • 更好地认识浏览器和 Web
"When in doubt, WebIDL"

WebIDL for APIs


[Exposed=Window]
interface Student {
  constructor();
  attribute unsigned long id;
  stringifier attribute DOMString name;
};

var s = new Student();
s.id = 12345678;
s.name = '周杰倫';

var greeting = 'Hello, ' + s + '!';  // Now greeting == 'Hello, 周杰倫!'.

一些重要语法


[extended_attributes]
interface identifier {
  /* interface_members... */
};

constructor  //构造新对象,初始化为 this 或抛出异常

stringifier  //关键字,非默认字符串转换

unsigned long  //Type 的一种,[0, 4294967295]

DOMString  //所有可能的 code units 序列的集合,不包含 null

WebIDL for APIs

[SecureContext, Exposed=Window]
interface PaymentRequest : EventTarget {
  constructor(
    sequence<PaymentMethodData> methodData,
    PaymentDetailsInit details,
    optional PaymentOptions options = {}
  );
  [NewObject]
  Promise<PaymentResponse> show(optional Promise<PaymentDetailsUpdate> detailsPromise);
  readonly attribute DOMString? shippingOption;
}

一些重要语法


[NewObject]  //方法的引用者总是一个对象实例

SecureContext  //Secure Contexts 规范定义的安全上下文

Promise  //参考 Writing Promise-Using Specifications

DOMString?  // nullable DOMString

WebIDL for APIs

[Exposed=(Window,Worker)]
interface Performance : EventTarget {
    DOMHighResTimeStamp now();
    readonly attribute DOMHighResTimeStamp timeOrigin;
    [Default] object toJSON();
};
partial interface mixin WindowOrWorkerGlobalScope {
    [Replaceable] readonly attribute Performance performance;
};

一些重要语法


interface mixin  //多个接口可共用的方法和属性

partial interface  //可在多个规范定义同一个interface

[Default]  //默认行为算法必须执行

[Replaceable]  //可后续指定值

Throw a TypeError  //Web IDL 不可自定义 exception

试试 Web IDL?

工具:BikeshedReSpec


<pre class="idl">
interface Request {
  readonly attribute ByteString method;
  readonly attribute USVString url;
};
</pre>

用 Web IDL 捉虫

API 实现有 bug?--> 看标准,找wpt.fyi,提bug

idl test in wpt

用 Web IDL 做设计

  • Explainer 开始
  • 参考 TAG 的 Client-side API Design Principles
  • 通过 GitHub 和 社区组寻找志同道合的开发者
Client-side API Design Principles by the TAG

几个问题?

WebAssembly & Web IDL Bindings - Luke Wagner

Web 需要你的力量!

欢迎提问?