WebTransport API
The WebTransport() constructor creates a new WebTransport object instance.
Syntax
new WebTransport(url)
new WebTransport(url, options)
Parameters
url- : A string representing the URL of the HTTP/3 server to connect to. The scheme must be HTTPS, and the port number needs to be explicitly specified.
options- : An object that may have the following properties:
-
allowPooling- : A boolean value.
If
true, the network connection for this WebTransport can be shared with a pool of other HTTP/3 sessions. By default the value isfalse, and the connection cannot be shared.
- : A boolean value.
If
-
anticipatedConcurrentIncomingBidirectionalStreams-
: An integer between
0and65535, ornull, that indicates the number of incoming bidirectional streams that the application expects the server to have open at the same time.This is a hint that the browser can use to raise its limit on server-opened streams in advance. By default the value is
null, and no hint is given. The value is available afterwards in the WebTransport.anticipatedConcurrentIncomingBidirectionalStreams property.
-
-
anticipatedConcurrentIncomingUnidirectionalStreams-
: An integer between
0and65535, ornull, that indicates the number of incoming unidirectional streams that the application expects the server to have open at the same time.This is a hint that the browser can use to raise its limit on server-opened streams in advance. By default the value is
null, and no hint is given. The value is available afterwards in the WebTransport.anticipatedConcurrentIncomingUnidirectionalStreams property.
-
-
congestionControl- : A string indicating the application's preference that the congestion control algorithm used when sending data over this connection be tuned for either throughput or low-latency.
This is a hint to the user agent.
The allowed values are:
default(default),throughput, andlow-latency.
- : A string indicating the application's preference that the congestion control algorithm used when sending data over this connection be tuned for either throughput or low-latency.
This is a hint to the user agent.
The allowed values are:
-
datagramsReadableType-
: A string that sets the type of the ReadableStream that the new transport uses for incoming datagrams. You access this stream as
transport.datagrams.readable(see WebTransport.datagrams and WebTransportDatagramDuplexStream.readable). The only allowed value isbytes, which creates a readable byte stream. This stream can be read with a ReadableStreamBYOBReader, which reads each datagram into a buffer that you supply. If this option is omitted, the transport creates a default readable stream, in which each chunk is a new Uint8Array containing one datagram.Reading into your own buffer lets you reuse the same memory for every datagram, instead of the browser allocating new memory for each one. This is most useful when an application receives datagrams at a high rate, for example to deliver frequent game state or sensor updates.
Unless you use the ReadableStreamBYOBReader.read#min option, each read returns one datagram. If the supplied buffer is smaller than the datagram, the stream is errored, and the pending ReadableStreamBYOBReader.read() rejects with a RangeError. To avoid this, use a buffer of at least 64 KiB (65536 bytes), which is the recommended maximum size of the QUIC frames that carry datagrams. Use a Uint8Array as the view passed to
read(): a DataView or a typed array with multi-byte elements errors the stream, andread()rejects with a TypeError.[!NOTE] A byte stream doesn't fully preserve datagram boundaries: empty datagrams are not delivered, and reading with the
minoption can combine several datagrams into one read.
-
-
headers-
: An object literal, array, or Headers object that can be used to add custom HTTP request headers to the extended
CONNECTrequest that sets up the session. This allows information such as authentication tokens to be sent to the server in request headers when the session is established, rather than in the URL query string. By default, the value is{}, and no custom headers are added.The value has the same form as the
initparameter of the Headers.Headers constructor: an object literal with string values, an array of two-item[name, value]arrays, or an existingHeadersobject. Forbidden request headers, such as Cookie, are silently ignored. TheWT-Available-Protocolsheader can't be set using this option, and is instead set from the values inprotocols.The headers that the server sends in its response, other than
WT-Protocol, can be read from WebTransport.responseHeaders once the session is established.
-
-
protocols-
: An array of strings, each indicating an application-specific protocol name, listed in order of preference. By default, the value is an empty array.
The server may select and return one of the protocols. In this case, the selected value becomes available in the WebTransport/protocol property once the WebTransport/ready promise fulfills. The server may also choose not to select any of the offered protocols, in which case
protocolwill return an empty string (""). The server may also reject the connection if it doesn't support any of the protocols, in which case WebTransport/ready will reject with an error.
-
-
requireUnreliable- : A boolean value.
If
true, the connection cannot be established over HTTP/2 if an HTTP/3 connection is not possible. By default, the value isfalse.
- : A boolean value.
If
-
serverCertificateHashes-
: An array of objects, each defining the hash value of a server certificate along with the name of the algorithm that was used to generate it. This option is only supported for transports using dedicated connections (
allowPoolingisfalse).If specified, the browser will attempt to authenticate the certificate provided by the server against the provided certificate hash(es) in order to connect, instead of using the Web public key infrastructure (PKI). If any hashes match, the browser knows that the server possesses a trusted certificate and will connect as normal. If empty, the user agent uses the same PKI certificate verification procedures it would use for a normal fetch operation.
This feature allows developers to connect to WebTransport servers that would normally find it challenging to obtain a publicly trusted certificate, such as hosts that are not publicly routable, or ephemeral hosts like virtual machines.
[!NOTE] The web application might typically fetch the hashes from a trusted intermediary. For example, you might use a cloud provider to provision VMs that run your WebTransport servers. The provider has trusted access to the server and can request its certificate, generate hashes, and provide these to the application via an API (mediated via PKI) or a cloud console. The web application can now connect directly to the VM-hosted server using the supplied hashes, even though the VM itself does not have a long-lived TLS certificate.
The certificate must be an X.509v3 certificate with a validity period of less than 2 weeks, and the current time must be within that validity period. The format of the public key in the certificate depends on the implementation, but must minimally include ECDSA with the secp256r1 (NIST P-256) named group, and must not include RSA keys. An ECDSA key is, therefore, an interoperable default public key format. A user agent may add further requirements; these will be listed in the browser compatibility section if known.
Each object in the array has the following properties:
-
algorithm- : A string with the value:
sha-256(case-insensitive). Note that this string represents the algorithm to use to verify the hash, and that any hash using an unknown algorithm will be ignored. At the time of writing,SHA-256is the only hash algorithm listed in the specification.
- : A string with the value:
-
value- : An
ArrayBuffer, TypedArray orDataViewcontaining the hash value.
- : An
-
-
-
- : An object that may have the following properties:
Return value
A new WebTransport object.
Exceptions
NotSupportedErrorDOMException- : Thrown if
serverCertificateHashesis specified but the transport protocol does not support this feature.
- : Thrown if
SyntaxError- : Thrown if the specified
urlis invalid, if the scheme is not HTTPS, or if the URL includes a fragment. Also thrown ifprotocolscontains a duplicate value, a value with characters not allowed in a protocol token, or a value whose encoded length is0or greater than512bytes.
- : Thrown if the specified
- TypeError
- : Thrown if a
serverCertificateHashesis set for a non-dedicated connection (in other words, ifallowPoolingistrue). Also thrown ifanticipatedConcurrentIncomingBidirectionalStreamsoranticipatedConcurrentIncomingUnidirectionalStreamsis outside the range0to65535. Also thrown ifheaderscontains an entry that isn't a two-item array, an invalid header name or value, or a header namedWT-Available-Protocols(case-insensitive).
- : Thrown if a
Examples
Connecting with default options
This example shows how you might construct a WebTransport using just a URL, wait for it to connect, and then monitor the transport and report when it closes.
First, we define an async method that takes a URL and uses it to construct the WebTransport object.
No constructor options are specified, so the connection uses default options: dedicated connection, support for unreliable transports isn't required, default congestion control, and normal Web PKI authentication with the server.
Note that the scheme must be HTTPS, and the port number must be explicitly specified.
Once the WebTransport.ready promise fulfills, you can start using the connection.
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
return transport;
}
You can respond to the connection closing by waiting for the WebTransport.closed promise to fulfill.
Errors returned by WebTransport operations are of type WebTransportError, and contain additional data on top of the standard DOMException set.
The closeTransport() method below shows how.
Within a try...catch block, it uses await to wait for the closed promise to fulfill or reject, and then reports whether or not the connection closed intentionally or due to an error.
async function closeTransport(transport) {
// Respond to connection closing
try {
await transport.closed;
console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
} catch (error) {
console.error(`The HTTP/3 connection to ${url} closed due to ${error}.`);
}
}
We might call the asynchronous functions above in their own asynchronous function, as shown below.
// Use the transport
async function useTransport(url) {
const transport = await initTransport(url);
// Use the transport object to send and receive data
// …
// When done, close the transport
await closeTransport(transport);
}
const url = "https://example.com:4999/wt";
useTransport(url);
Connecting with server certificate hashes
The example below shows the code to construct a WebTransport that specifies the serverCertificateHashes option.
In this case, the array contains two hashes, both encoded using the SHA-256 algorithm.
Note that the allowPooling option must be false (the default).
The value of each hash can be an ArrayBuffer, a TypedArray (for example, a Uint8Array), or a DataView. The example below represents each SHA-256 hash value as a Uint8Array; for example, the hexadecimal string 5a1559... corresponds to the byte values 0x5a, 0x15, 0x59, and so on.
const transport = new WebTransport(url, {
serverCertificateHashes: [
{
// 5a155927eba7996228455e4721e6fe5f739ae15db6915d765e5db302b4f8a274
algorithm: "sha-256",
value: new Uint8Array([
0x5a, 0x15, 0x59, 0x27, 0xeb, 0xa7, 0x99, 0x62, 0x28, 0x45, 0x5e, 0x47,
0x21, 0xe6, 0xfe, 0x5f, 0x73, 0x9a, 0xe1, 0x5d, 0xb6, 0x91, 0x5d, 0x76,
0x5e, 0x5d, 0xb3, 0x02, 0xb4, 0xf8, 0xa2, 0x74,
]),
},
{
// 7d7094e7a8d3097feff3b5ee84fa5cab58e4de78f38bcfdee5ea8b51f4bfa8fd
algorithm: "sha-256",
value: new Uint8Array([
0x7d, 0x70, 0x94, 0xe7, 0xa8, 0xd3, 0x09, 0x7f, 0xef, 0xf3, 0xb5, 0xee,
0x84, 0xfa, 0x5c, 0xab, 0x58, 0xe4, 0xde, 0x78, 0xf3, 0x8b, 0xcf, 0xde,
0xe5, 0xea, 0x8b, 0x51, 0xf4, 0xbf, 0xa8, 0xfd,
]),
},
],
});
Reading datagrams with a BYOB reader
This example shows how to read incoming datagrams into a buffer that you supply, using a ReadableStreamBYOBReader.
First, we construct the WebTransport with the datagramsReadableType option set to bytes, so that the transport's WebTransportDatagramDuplexStream.readable property returns a readable byte stream.
We then get a BYOB ("bring your own buffer") reader by passing mode: "byob" to ReadableStream.getReader().
We allocate a 64 KiB buffer, which is large enough to hold any datagram (see the datagramsReadableType option).
Each call to ReadableStreamBYOBReader.read() fills a view of this buffer with one datagram.
The returned value is a new Uint8Array over the same memory, sized to fit the datagram.
Passing a view to read() transfers its buffer, so the original can no longer be used.
Instead, we take the buffer from value and reuse it for the next read.
const transport = new WebTransport(url, { datagramsReadableType: "bytes" });
await transport.ready;
const reader = transport.datagrams.readable.getReader({ mode: "byob" });
let buffer = new ArrayBuffer(65536);
while (true) {
const { value, done } = await reader.read(new Uint8Array(buffer));
if (done) {
break;
}
// value is a Uint8Array containing one datagram
console.log(`Received a datagram of ${value.byteLength} bytes`);
buffer = value.buffer;
}
Setting custom request headers
This example shows the three ways that you can use the headers option to add custom headers to the request that sets up the session.
First we pass an object literal, where each property name is a header name and its value is the header value:
const transport = new WebTransport(url, {
headers: {
Authorization: "Bearer abc123",
"X-Client-Version": "2.4.1",
},
});
You can also pass an array of two-item [name, value] arrays:
const transport = new WebTransport(url, {
headers: [
["Authorization", "Bearer abc123"],
["X-Client-Version", "2.4.1"],
],
});
You can also pass a Headers object:
const headers = new Headers();
headers.append("Authorization", "Bearer abc123");
headers.append("X-Client-Version", "2.4.1");
const transport = new WebTransport(url, { headers });
Specifications
Browser compatibility
See also
- Using WebTransport
- WebSockets API
- Streams API
- WebTransport over HTTP/3
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
