repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/api/websockets_api | data/mdn-content/files/en-us/web/api/websockets_api/writing_a_websocket_server_in_java/index.md | ---
title: Writing a WebSocket server in Java
slug: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java
page-type: guide
---
{{DefaultAPISidebar("WebSockets API")}}
This example shows you how to create a WebSocket API server using Oracle Java.
Although other server-side languages can be used to create a WebSocket server, this example uses Oracle Java to simplify the example code.
This server conforms to [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455), so it only handles connections from Chrome version 16, Firefox 11, IE 10 and higher.
## First steps
WebSockets communicate over a [TCP (Transmission Control Protocol)](https://en.wikipedia.org/wiki/Transmission_Control_Protocol) connection. Java's [ServerSocket](https://docs.oracle.com/javase/8/docs/api/java/net/ServerSocket.html) class is located in the `java.net` package.
### ServerSocket
The `ServerSocket` constructor accepts a single parameter `port` of type `int`.
When you instantiate the ServerSocket class, it is bound to the port number you specified by the _port_ argument.
Here's an implementation split into parts:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WebSocket {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
ServerSocket server = new ServerSocket(80);
try {
System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection…");
Socket client = server.accept();
System.out.println("A client connected.");
```
### Socket Methods
- `java.net.Socket.getInputStream()`
- : Returns an input stream for this socket.
- `java.net.Socket.getOutputStream()`
- : Returns an output stream for this socket.
### OutputStream Methods
```java
write(byte[] b, int off, int len)
```
Writes `len` bytes from the specified byte array starting at offset `off` to this output stream.
### InputStream Methods
```java
read(byte[] b, int off, int len)
```
Reads up to _len_ bytes of data from the input stream into an array of bytes.
Let us extend our example.
```java
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
Scanner s = new Scanner(in, "UTF-8");
```
## Handshaking
When a client connects to a server, it sends a GET request to upgrade the connection to a WebSocket from a simple HTTP request. This is known as handshaking.
```java
try {
String data = s.useDelimiter("\\r\\n\\r\\n").next();
Matcher get = Pattern.compile("^GET").matcher(data);
```
Creating the response is easier than understanding why you must do it in this way.
You must,
1. Obtain the value of _Sec-WebSocket-Key_ request header without any leading and trailing whitespace
2. Link it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
3. Compute SHA-1 and Base64 code of it
4. Write it back as value of _Sec-WebSocket-Accept_ response header as part of an HTTP response.
```java
if (get.find()) {
Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
match.find();
byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n"
+ "Connection: Upgrade\r\n"
+ "Upgrade: websocket\r\n"
+ "Sec-WebSocket-Accept: "
+ Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
+ "\r\n\r\n").getBytes("UTF-8");
out.write(response, 0, response.length);
```
## Decoding messages
After a successful handshake, client can send messages to the server, but now these are encoded.
If we send "abcdef", we get these bytes:
```plain
129 134 167 225 225 210 198 131 130 182 194 135
```
- 129:
| FIN (Is this the whole message?) | RSV1 | RSV2 | RSV3 | Opcode |
| -------------------------------- | ---- | ---- | ---- | -------- |
| 1 | 0 | 0 | 0 | 0x1=0001 |
FIN: You can send your message in frames, but now keep things simple.
Opcode _0x1_ means this is a text. [Full list of Opcodes](https://datatracker.ietf.org/doc/html/rfc6455#section-5.2)
- 134:
If the second byte minus 128 is between 0 and 125, this is the length of the message. If it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer, the most significant bit MUST be 0) are the length.
> **Note:** It can take 128 because the first bit is always 1.
- 167, 225, 225 and 210 are the bytes of the key to decode. It changes every time.
- The remaining encoded bytes are the message.
### Decoding algorithm
decoded byte = encoded byte XOR (position of encoded byte BITWISE AND 0x3)th byte of key
Example in Java:
```java
byte[] decoded = new byte[6];
byte[] encoded = new byte[] { (byte) 198, (byte) 131, (byte) 130, (byte) 182, (byte) 194, (byte) 135 };
byte[] key = new byte[] { (byte) 167, (byte) 225, (byte) 225, (byte) 210 };
for (int i = 0; i < encoded.length; i++) {
decoded[i] = (byte) (encoded[i] ^ key[i & 0x3]);
}
}
} finally {
s.close();
}
} finally {
server.close();
}
}
}
```
## Related
- [Writing WebSocket servers](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers)
| 0 |
data/mdn-content/files/en-us/web/api/websockets_api | data/mdn-content/files/en-us/web/api/websockets_api/writing_websocket_server/index.md | ---
title: Writing a WebSocket server in C#
slug: Web/API/WebSockets_API/Writing_WebSocket_server
page-type: guide
---
{{DefaultAPISidebar("WebSockets API")}}
If you would like to use the WebSocket API, it is useful if you have a server. In this article I will show you how to write one in C#. You can do it in any server-side language, but to keep things simple and more understandable, I chose Microsoft's language.
This server conforms to [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455), so it will only handle connections from Chrome version 16, Firefox 11, IE 10 and over.
## First steps
WebSockets communicate over a [TCP (Transmission Control Protocol)](https://en.wikipedia.org/wiki/Transmission_Control_Protocol) connection. Luckily, C# has a [TcpListener](https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcplistener?view=net-6.0) class which does as the name suggests. It is in the `System.Net.Sockets` namespace.
> **Note:** It is a good idea to include the namespace with the `using` keyword in order to write less. It allows usage of a namespace's classes without typing the full namespace every time.
### TcpListener
Constructor:
```cs
TcpListener(System.Net.IPAddress localaddr, int port)
```
`localaddr` specifies the IP of the listener, and `port` specifies the port.
> **Note:** To create an `IPAddress` object from a `string`, use the `Parse` static method of `IPAddress`.
Methods:
- `Start()`
- `System.Net.Sockets.TcpClient AcceptTcpClient()`
Waits for a Tcp connection, accepts it and returns it as a TcpClient object.
Here's a barebones server implementation:
```cs
using System.Net.Sockets;
using System.Net;
using System;
class Server {
public static void Main() {
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
Console.WriteLine("Server has started on 127.0.0.1:80.{0}Waiting for a connection…", Environment.NewLine);
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");
}
}
```
### TcpClient
Methods:
- `System.Net.Sockets.NetworkStream GetStream()`
Gets the stream which is the communication channel. Both sides of the channel have reading and writing capability.
Properties:
- `int Available`
This Property indicates how many bytes of data have been sent. The value is zero until `NetworkStream.DataAvailable` is _true_.
### NetworkStream
Methods:
- Writes bytes from buffer, offset and size determine length of message.
```cs
Write(byte[] buffer, int offset, int size)
```
- Reads bytes to `buffer`. `offset` and `size` determine the length of the message.
```cs
Read(byte[] buffer, int offset, int size)
```
Let us extend our example.
```cs
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");
NetworkStream stream = client.GetStream();
//enter to an infinite cycle to be able to handle every change in stream
while (true) {
while (!stream.DataAvailable);
byte[] bytes = new byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
}
```
## Handshaking
When a client connects to a server, it sends a GET request to upgrade the connection to a WebSocket from a simple HTTP request. This is known as handshaking.
This sample code can detect a GET from the client. Note that this will block until the first 3 bytes of a message are available. Alternative solutions should be investigated for production environments.
```cs
using System.Text;
using System.Text.RegularExpressions;
while(client.Available < 3)
{
// wait for enough bytes to be available
}
byte[] bytes = new byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
//translate bytes of request to string
String data = Encoding.UTF8.GetString(bytes);
if (Regex.IsMatch(data, "^GET")) {
} else {
}
```
The response is easy to build, but might be a little difficult to understand. The full explanation of the Server handshake can be found in RFC 6455, section 4.2.2. For our purposes, we'll just build a simple response.
You must:
1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
3. Compute SHA-1 and Base64 hash of the new value
4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
```cs
if (new System.Text.RegularExpressions.Regex("^GET").IsMatch(data))
{
const string eol = "\r\n"; // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol
+ "Connection: Upgrade" + eol
+ "Upgrade: websocket" + eol
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
System.Security.Cryptography.SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + eol
+ eol);
stream.Write(response, 0, response.Length);
}
```
## Decoding messages
After a successful handshake, the client will send encoded messages to the server.
If we send "MDN", we get these bytes:
```plain
129 131 61 84 35 6 112 16 109
```
Let's take a look at what these bytes mean.
The first byte, which currently has a value of 129, is a bitfield that breaks down as such:
| FIN (Bit 0) | RSV1 (Bit 1) | RSV2 (Bit 2) | RSV3 (Bit 3) | Opcode (Bit 4:7) |
| ----------- | ------------ | ------------ | ------------ | ---------------- |
| 1 | 0 | 0 | 0 | 0x1=0001 |
- FIN bit: This bit indicates whether the full message has been sent from the client. Messages may be sent in frames, but for now we will keep things simple.
- RSV1, RSV2, RSV3: These bits must be 0 unless an extension is negotiated which supplies a nonzero value to them.
- Opcode: These bits describe the type of message received. Opcode 0x1 means this is a text message. [Full list of Opcodes](https://datatracker.ietf.org/doc/html/rfc6455#section-5.2)
The second byte, which currently has a value of 131, is another bitfield that breaks down as such:
| MASK (Bit 0) | Payload Length (Bit 1:7) |
| ------------ | ------------------------ |
| 1 | 0x83=0000011 |
- MASK bit: Defines whether the "Payload data" is masked. If set to 1, a masking key is present in Masking-Key, and this is used to unmask the "Payload data". All messages from the client to the server have this bit set.
- Payload Length: If this value is between 0 and 125, then it is the length of message. If it is 126, the following 2 bytes (16-bit unsigned integer) are the length. If it is 127, the following 8 bytes (64-bit unsigned integer) are the length.
> **Note:** Because the first bit is always 1 for client-to-server messages, you can subtract 128 from this byte to get rid of the MASK bit.
Note that the MASK bit is set in our message. This means that the next four bytes (61, 84, 35, and 6) are the mask bytes used to decode the message. These bytes change with every message.
The remaining bytes are the encoded message payload.
### Decoding algorithm
_D_i_ = _E_i_ XOR _M_\_(_i_ mod 4)
where _D_ is the decoded message array, _E_ is the encoded message array, _M_ is the mask byte array, and _i_ is the index of the message byte to decode.
Example in C#:
```cs
byte[] decoded = new byte[3];
byte[] encoded = new byte[3] {112, 16, 109};
byte[] mask = new byte[4] {61, 84, 35, 6};
for (int i = 0; i < encoded.Length; i++) {
decoded[i] = (byte)(encoded[i] ^ mask[i % 4]);
}
```
## Put together
### wsserver.cs
```cs
//
// csc wsserver.cs
// wsserver.exe
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
class Server {
public static void Main() {
string ip = "127.0.0.1";
int port = 80;
var server = new TcpListener(IPAddress.Parse(ip), port);
server.Start();
Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection…", ip, port);
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");
NetworkStream stream = client.GetStream();
// enter to an infinite cycle to be able to handle every change in stream
while (true) {
while (!stream.DataAvailable);
while (client.Available < 3); // match against "get"
byte[] bytes = new byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
string s = Encoding.UTF8.GetString(bytes);
if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase)) {
Console.WriteLine("=====Handshaking from client=====\n{0}", s);
// 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
// 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
// 3. Compute SHA-1 and Base64 hash of the new value
// 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);
// HTTP/1.1 defines the sequence CR LF as the end-of-line marker
byte[] response = Encoding.UTF8.GetBytes(
"HTTP/1.1 101 Switching Protocols\r\n" +
"Connection: Upgrade\r\n" +
"Upgrade: websocket\r\n" +
"Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");
stream.Write(response, 0, response.Length);
} else {
bool fin = (bytes[0] & 0b10000000) != 0,
mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
int opcode = bytes[0] & 0b00001111, // expecting 1 - text message
offset = 2;
ulong msglen = bytes[1] & (ulong)0b01111111;
if (msglen == 126) {
// bytes are reversed because websocket will print them in Big-Endian, whereas
// BitConverter will want them arranged in little-endian on windows
msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
offset = 4;
} else if (msglen == 127) {
// To test the below code, we need to manually buffer larger messages — since the NIC's autobuffering
// may be too latency-friendly for this code to run (that is, we may have only some of the bytes in this
// websocket frame available through client.Available).
msglen = BitConverter.ToUInt64(new byte[] { bytes[9], bytes[8], bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2] },0);
offset = 10;
}
if (msglen == 0) {
Console.WriteLine("msglen == 0");
} else if (mask) {
byte[] decoded = new byte[msglen];
byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
offset += 4;
for (ulong i = 0; i < msglen; ++i)
decoded[i] = (byte)(bytes[offset + i] ^ masks[i % 4]);
string text = Encoding.UTF8.GetString(decoded);
Console.WriteLine("{0}", text);
} else
Console.WriteLine("mask bit not set");
Console.WriteLine();
}
}
}
}
```
### client.html
```html
<!doctype html>
<html lang="en">
<style>
textarea {
vertical-align: bottom;
}
#output {
overflow: auto;
}
#output > p {
overflow-wrap: break-word;
}
#output span {
color: blue;
}
#output span.error {
color: red;
}
</style>
<body>
<h2>WebSocket Test</h2>
<textarea cols="60" rows="6"></textarea>
<button>send</button>
<div id="output"></div>
</body>
<script>
// http://www.websocket.org/echo.html
const button = document.querySelector("button");
const output = document.querySelector("#output");
const textarea = document.querySelector("textarea");
const wsUri = "ws://127.0.0.1/";
const websocket = new WebSocket(wsUri);
button.addEventListener("click", onClickButton);
websocket.onopen = (e) => {
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
};
websocket.onclose = (e) => {
writeToScreen("DISCONNECTED");
};
websocket.onmessage = (e) => {
writeToScreen(`<span>RESPONSE: ${e.data}</span>`);
};
websocket.onerror = (e) => {
writeToScreen(`<span class="error">ERROR:</span> ${e.data}`);
};
function doSend(message) {
writeToScreen(`SENT: ${message}`);
websocket.send(message);
}
function writeToScreen(message) {
output.insertAdjacentHTML("afterbegin", `<p>${message}</p>`);
}
function onClickButton() {
const text = textarea.value;
text && doSend(text);
textarea.value = "";
textarea.focus();
}
</script>
</html>
```
## Related
- [Writing WebSocket servers](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers)
| 0 |
data/mdn-content/files/en-us/web/api/websockets_api | data/mdn-content/files/en-us/web/api/websockets_api/writing_websocket_client_applications/index.md | ---
title: Writing WebSocket client applications
slug: Web/API/WebSockets_API/Writing_WebSocket_client_applications
page-type: guide
---
{{DefaultAPISidebar("WebSockets API")}}
WebSocket client applications use the [WebSocket API](/en-US/docs/Web/API/WebSockets_API) to communicate with [WebSocket servers](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers) using the WebSocket protocol.
{{AvailableInWorkers}}
> **Note:** The example snippets in this article are taken from our WebSocket chat client/server sample.
> [See the code](https://github.com/mdn/samples-server/tree/master/s/websocket-chat).
## Creating a WebSocket object
In order to communicate using the WebSocket protocol, you need to create a {{domxref("WebSocket")}} object; this will automatically attempt to open the connection to the server.
The WebSocket constructor accepts one required and one optional parameter:
```js
webSocket = new WebSocket(url, protocols);
```
- `url`
- : The URL to which to connect; this should be the URL to which the WebSocket server will respond.
This should use the URL scheme `wss://`, although some software may allow you to use the insecure `ws://` for local connections.
- `protocols` {{ optional_inline() }}
- : Either a single protocol string or an array of protocol strings.
These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified `protocol`).
If you don't specify a protocol string, an empty string is assumed.
The constructor will throw a `SecurityError` if the destination doesn't allow access.
This may happen if you attempt to use an insecure connection (most {{Glossary("user agent", "user agents")}} now require a secure link for all WebSocket connections unless they're on the same device or possibly on the same network).
### Connection errors
If an error occurs while attempting to connect, first a simple event with the name `error` is sent to the {{domxref("WebSocket")}} object (thereby invoking its {{domxref("WebSocket/error_event", "onerror")}} handler), and then the {{domxref("CloseEvent")}} is sent to the `WebSocket` object (thereby invoking its {{domxref("WebSocket/close_event", "onclose")}} handler) to indicate the reason for the connection's closing.
The browser may also output to its console a more descriptive error message as well as a closing code as defined in [RFC 6455, Section 7.4](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4) through the {{domxref("CloseEvent")}}.
### Examples
This simple example creates a new WebSocket, connecting to the server at `wss://www.example.com/socketserver`.
A custom protocol of "protocolOne" is named in the request for the socket in this example, though this can be omitted.
```js
const exampleSocket = new WebSocket(
"wss://www.example.com/socketserver",
"protocolOne",
);
```
On return, {{domxref("WebSocket.readyState", "exampleSocket.readyState")}} is `CONNECTING`. The `readyState` will become `OPEN` once
the connection is ready to transfer data.
If you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols:
```js
const exampleSocket = new WebSocket("wss://www.example.com/socketserver", [
"protocolOne",
"protocolTwo",
]);
```
Once the connection is established (that is, `readyState` is `OPEN`), {{domxref("WebSocket.protocol", "exampleSocket.protocol")}} will tell you which protocol the server selected.
Establishing a WebSocket relies on the [HTTP Upgrade mechanism](/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism), so the request for the protocol upgrade is implicit when we address the web server as `ws://www.example.com` or `wss://www.example.com`.
## Sending data to the server
Once you've opened your connection, you can begin transmitting data to the server.
To do this, call the `WebSocket` object's {{domxref("WebSocket.send", "send()")}} method for each message you want to send:
```js
exampleSocket.send("Here's some text that the server is urgently awaiting!");
```
You can send data as a string, {{ domxref("Blob") }}, or {{jsxref("ArrayBuffer")}}.
As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the `send()` method immediately after creating a WebSocket object will be successful.
We can at least be sure that attempting to send data only takes place once a connection is established by defining an {{domxref("WebSocket/open_event", "onopen")}} event handler to do the work:
```js
exampleSocket.onopen = (event) => {
exampleSocket.send("Here's some text that the server is urgently awaiting!");
};
```
### Using JSON to transmit objects
One handy thing you can do is use {{glossary("JSON")}} to send reasonably complex data
to the server. For example, a chat program can interact with a server using a protocol
implemented using packets of JSON-encapsulated data:
```js
// Send text to all users through the server
function sendText() {
// Construct a msg object containing the data the server needs to process the message from the chat client.
const msg = {
type: "message",
text: document.getElementById("text").value,
id: clientID,
date: Date.now(),
};
// Send the msg object as a JSON-formatted string.
exampleSocket.send(JSON.stringify(msg));
// Blank the text input element, ready to receive the next line of text from the user.
document.getElementById("text").value = "";
}
```
## Receiving messages from the server
WebSockets is an event-driven API; when messages are received, a `message`
event is sent to the `WebSocket` object. To handle it, add an event listener
for the `message` event, or use the {{domxref("WebSocket/message_event",
"onmessage")}} event handler. To begin listening for incoming data, you can do something
like this:
```js
exampleSocket.onmessage = (event) => {
console.log(event.data);
};
```
### Receiving and interpreting JSON objects
Let's consider the chat client application first alluded to in [Using JSON to transmit objects](#using_json_to_transmit_objects). There are assorted types of data packets the client might receive, such as:
- Login handshake
- Message text
- User list updates
The code that interprets these incoming messages might look like this:
```js
exampleSocket.onmessage = (event) => {
const f = document.getElementById("chatbox").contentDocument;
let text = "";
const msg = JSON.parse(event.data);
const time = new Date(msg.date);
const timeStr = time.toLocaleTimeString();
switch (msg.type) {
case "id":
clientID = msg.id;
setUsername();
break;
case "username":
text = `User <em>${msg.name}</em> signed in at ${timeStr}<br>`;
break;
case "message":
text = `(${timeStr}) ${msg.name} : ${msg.text} <br>`;
break;
case "rejectusername":
text = `Your username has been set to <em>${msg.name}</em> because the name you chose is in use.<br>`;
break;
case "userlist":
document.getElementById("userlistbox").innerHTML = msg.users.join("<br>");
break;
}
if (text.length) {
f.write(text);
document.getElementById("chatbox").contentWindow.scrollByPages(1);
}
};
```
Here we use {{jsxref("JSON.parse()")}} to convert the JSON object back into the original object, then examine and act upon its contents.
### Text data format
Text received over a WebSocket connection is in UTF-8 format.
## Closing the connection
When you've finished using the WebSocket connection, call the WebSocket method {{domxref("WebSocket.close", "close()")}}:
```js
exampleSocket.close();
```
It may be helpful to examine the socket's {{domxref("WebSocket.bufferedAmount", "bufferedAmount")}} attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network.
If this value isn't 0, there's pending data still, so you may wish to wait before closing the connection.
## Security considerations
WebSockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure WebSocket connection from a page loaded using HTTPS or vice versa.
Most browsers now only allow secure WebSocket connections, and no longer support using them in insecure contexts.
| 0 |
data/mdn-content/files/en-us/web/api/websockets_api | data/mdn-content/files/en-us/web/api/websockets_api/writing_a_websocket_server_in_javascript_deno/index.md | ---
title: Writing a WebSocket server in JavaScript (Deno)
slug: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_JavaScript_Deno
page-type: guide
---
{{DefaultAPISidebar("WebSockets API")}}
This example shows you how to create a WebSocket API server using Deno, with an accompanying web page.
Deno is a JavaScript runtime which supports TypeScript compiling and caching on the fly. Deno has built-in formatter, linter, test runner and more, and also implements many web APIs. By being compliant with the web standards, all Deno-specific APIs are implemented under the `Deno` namespace.
The [Deno website](https://deno.com/) provides instructions for installing Deno.
Deno version at the time of writing: `1.36`.
## Code
The code will be contained in two files, one for the server, and one for the client.
### Server
Create a `main.js` file. This file will contain the code for a simple HTTP server which will also serve the client HTML.
```js
Deno.serve({
port: 80,
handler: async (request) => {
// If the request is a websocket upgrade,
// we need to use the Deno.upgradeWebSocket helper
if (request.headers.get("upgrade") === "websocket") {
const { socket, response } = Deno.upgradeWebSocket(request);
socket.onopen = () => {
console.log("CONNECTED");
};
socket.onmessage = (event) => {
console.log(`RECEIVED: ${event.data}`);
socket.send("pong");
};
socket.onclose = () => console.log("DISCONNECTED");
socket.onerror = (error) => console.error("ERROR:", error);
return response;
} else {
// If the request is a normal HTTP request,
// we serve the client HTML file.
const file = await Deno.open("./index.html", { read: true });
return new Response(file.readable);
}
},
});
```
`Deno.upgradeWebSocket()` upgrades the connection to a WebSocket connection, which is explained further in [Protocol upgrade mechanism](/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism).
[`Deno.serve()`](https://deno.land/[email protected]?s=Deno.serve) uses `Deno.listen()` and `Deno.serveHttp()` under the hood, and is a higher-level interface to easily set up a HTTP server. Without it, the code would look something like this.
```js
for await (const conn of Deno.listen({ port: 80 })) {
for await (const { request, respondWith } of Deno.serveHttp(conn)) {
respondWith(handler(request));
}
}
```
### Client
Create an `index.html` file. This file will contain a script that will ping the server every five seconds after a connection has been made.
```html
<!doctype html>
<h2>WebSocket Test</h2>
<p>Sends a ping every five seconds</p>
<div id="output"></div>
<script>
const wsUri = "ws://127.0.0.1/";
const output = document.querySelector("#output");
const websocket = new WebSocket(wsUri);
let pingInterval;
function writeToScreen(message) {
output.insertAdjacentHTML("afterbegin", `<p>${message}</p>`);
}
function sendMessage(message) {
writeToScreen(`SENT: ${message}`);
websocket.send(message);
}
websocket.onopen = (e) => {
writeToScreen("CONNECTED");
sendMessage("ping");
pingInterval = setInterval(() => {
sendMessage("ping");
}, 5000);
};
websocket.onclose = (e) => {
writeToScreen("DISCONNECTED");
clearInterval(pingInterval);
};
websocket.onmessage = (e) => {
writeToScreen(`RECEIVED: ${e.data}`);
};
websocket.onerror = (e) => {
writeToScreen(`ERROR: ${e.data}`);
};
</script>
```
## Running the code
With the two files, run the app using Deno.
```sh
deno run --allow-net=0.0.0.0:80 --allow-read=./index.html main.js
```
Deno requires us to give explicit permissions for what we can access on the host machine.
- `--allow-net=0.0.0.0:80` allows the app to attach to localhost on port 80
- `--allow-read=./index.html` allows access to the HTML file for the client
## See also
- [Writing WebSocket servers](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/audiotracklist/index.md | ---
title: AudioTrackList
slug: Web/API/AudioTrackList
page-type: web-api-interface
browser-compat: api.AudioTrackList
---
{{APIRef("HTML DOM")}}
The **`AudioTrackList`** interface is used to represent a list of the audio tracks contained within a given HTML media element, with each track represented by a separate {{domxref("AudioTrack")}} object in the list.
Retrieve an instance of this object with {{domxref('HTMLMediaElement.audioTracks')}}. The individual tracks can be accessed using array syntax.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("EventTarget")}}._
- {{domxref("AudioTrackList.length", "length")}} {{ReadOnlyInline}}
- : The number of tracks in the list.
## Instance methods
_This interface also inherits methods from its parent interface, {{domxref("EventTarget")}}._
- {{domxref("AudioTrackList.getTrackById", "getTrackById()")}}
- : Returns the {{domxref("AudioTrack")}} found within the `AudioTrackList` whose {{domxref("AudioTrack.id", "id")}} matches the specified string. If no match is found, `null` is returned.
## Events
- [`addtrack`](/en-US/docs/Web/API/AudioTrackList/addtrack_event)
- : Fired when a new audio track has been added to the media element.
- [`change`](/en-US/docs/Web/API/AudioTrackList/change_event)
- : Fired when a track has been enabled or disabled.
- [`removetrack`](/en-US/docs/Web/API/AudioTrackList/removetrack_event)
- : Fired when a new audio track has been removed from the media element.
## Usage notes
In addition to being able to obtain direct access to the audio tracks present on a media element, `AudioTrackList` lets you set event handlers on the {{domxref("AudioTrackList/addtrack_event", "addtrack")}} and {{domxref("AudioTrackList/removetrack_event", "removetrack")}} events, so that you can detect when tracks are added to or removed from the media element's stream. See the {{domxref("AudioTrackList/addtrack_event", "addtrack")}} and {{domxref("AudioTrackList/removetrack_event", "removetrack")}} events for details and examples.
## Examples
### Getting a media element's audio track list
To get a media element's {{domxref("AudioTrackList")}}, use its {{domxref("HTMLMediaElement.audioTracks", "audioTracks")}} property.
```js
const audioTracks = document.querySelector("video").audioTracks;
```
### Monitoring track count changes
In this example, we have an app that displays information about the number of channels available. To keep it up to date, handlers for the {{domxref("AudioTrackList/addtrack_event", "addtrack")}} and {{domxref("AudioTrackList/removetrack_event", "removetrack")}} events are set up.
```js
audioTracks.onaddtrack = updateTrackCount;
audioTracks.onremovetrack = updateTrackCount;
function updateTrackCount(event) {
trackCount = audioTracks.length;
drawTrackCountIndicator(trackCount);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audiotracklist | data/mdn-content/files/en-us/web/api/audiotracklist/length/index.md | ---
title: "AudioTrackList: length property"
short-title: length
slug: Web/API/AudioTrackList/length
page-type: web-api-instance-property
browser-compat: api.AudioTrackList.length
---
{{APIRef("HTML DOM")}}
The read-only **{{domxref("AudioTrackList")}}**
property **`length`** returns the number of entries in the
`AudioTrackList`, each of which is an {{domxref("AudioTrack")}}
representing one audio track in the media element. A value of 0 indicates that
there are no audio tracks in the media.
## Value
A number indicating how many audio tracks are included in the
`AudioTrackList`. Each track can be accessed by treating the
`AudioTrackList` as an array of objects of type {{domxref("AudioTrack")}}.
## Examples
This snippet gets the number of audio tracks in the first {{HTMLElement("video")}}
element found in the {{Glossary("DOM")}} by {{domxref("Document.querySelector",
"querySelector()")}}.
```js
const videoElem = document.querySelector("video");
let numAudioTracks = 0;
if (videoElem.audioTracks) {
numAudioTracks = videoElem.audioTracks.length;
}
```
Note that this sample checks to be sure {{domxref("HTMLMediaElement.audioTracks")}} is
defined, to avoid failing on browsers without support for {{domxref("AudioTrack")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/audiotracklist | data/mdn-content/files/en-us/web/api/audiotracklist/addtrack_event/index.md | ---
title: "AudioTrackList: addtrack event"
short-title: addtrack
slug: Web/API/AudioTrackList/addtrack_event
page-type: web-api-event
browser-compat: api.AudioTrackList.addtrack_event
---
{{APIRef}}
The `addtrack` event is fired when a track is added to an [`AudioTrackList`](/en-US/docs/Web/API/AudioTrackList).
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js-nolint
addEventListener("addtrack", (event) => { })
onaddtrack = (event) => { }
```
## Event type
A {{domxref("TrackEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("TrackEvent")}}
## Event properties
_`TrackEvent` is based on {{domxref("Event")}}, so properties of `Event` are also available on `TrackEvent` objects._
- {{domxref("TrackEvent.track", "track")}} {{ReadOnlyInline}}
- : The DOM track object the event is in reference to. If not `null`, this is always an object of one of the media track types: {{domxref("AudioTrack")}}, {{domxref("VideoTrack")}}, or {{domxref("TextTrack")}}).
## Description
### Trigger
The {{domxref("AudioTrackList/addtrack_event", "addtrack")}} event is called whenever a new track is added to the media
element whose audio tracks are represented by the `AudioTrackList` object.
This happens when tracks are added to the element when the media is first attached to
the element; one `addtrack` event will occur for each audio track in the
media resource.
This event is not cancelable and does not bubble.
### Use cases
You can use this event to react to a new audio track becoming available. You may want to update your UI elements to allow for user selection of the new audio track, for example.
## Examples
Using `addEventListener()`:
```js
const videoElement = document.querySelector("video");
videoElement.audioTracks.addEventListener("addtrack", (event) => {
console.log(`Audio track: ${event.track.label} added`);
});
```
Using the `onaddtrack` event handler property:
```js
const videoElement = document.querySelector("video");
videoElement.audioTracks.onaddtrack = (event) => {
console.log(`Audio track: ${event.track.label} added`);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Related events: [`removetrack`](/en-US/docs/Web/API/AudioTrackList/removetrack_event), [`change`](/en-US/docs/Web/API/AudioTrackList/change_event)
- This event on [`VideoTrackList`](/en-US/docs/Web/API/VideoTrackList) targets: [`addtrack`](/en-US/docs/Web/API/VideoTrackList/addtrack_event)
- This event on [`MediaStream`](/en-US/docs/Web/API/MediaStream) targets: [`addtrack`](/en-US/docs/Web/API/MediaStream/addtrack_event)
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/audiotracklist | data/mdn-content/files/en-us/web/api/audiotracklist/removetrack_event/index.md | ---
title: "AudioTrackList: removetrack event"
short-title: removetrack
slug: Web/API/AudioTrackList/removetrack_event
page-type: web-api-event
browser-compat: api.AudioTrackList.removetrack_event
---
{{APIRef}}
The `removetrack` event is fired when a track is removed from an [`AudioTrackList`](/en-US/docs/Web/API/AudioTrackList).
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js-nolint
addEventListener("removetrack", (event) => { })
onremovetrack = (event) => { }
```
## Event type
A {{domxref("TrackEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("TrackEvent")}}
## Event properties
_`TrackEvent` is based on {{domxref("Event")}}, so properties of `Event` are also available on `TrackEvent` objects._
- {{domxref("TrackEvent.track", "track")}} {{ReadOnlyInline}}
- : The DOM track object the event is in reference to. If not `null`, this is always an object of one of the media track types: {{domxref("AudioTrack")}}, {{domxref("VideoTrack")}}, or {{domxref("TextTrack")}}).
## Description
### Trigger
The {{domxref("AudioTrackList/removetrack_event", "removetrack")}} event is called whenever a track is removed from the media
element whose audio tracks are represented by the `AudioTrackList` object.
This event is not cancelable and does not bubble.
### Use cases
You can use this event to react to a new audio track becoming unavailable. You may want to update your UI elements to disallow for user selection of the removed audio track, for example.
## Examples
Using `addEventListener()`:
```js
const videoElement = document.querySelector("video");
videoElement.audioTracks.addEventListener("removetrack", (event) => {
console.log(`Audio track: ${event.track.label} removed`);
});
```
Using the `onremovetrack` event handler property:
```js
const videoElement = document.querySelector("video");
videoElement.audioTracks.onremovetrack = (event) => {
console.log(`Audio track: ${event.track.label} removed`);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Related events: [`addtrack`](/en-US/docs/Web/API/AudioTrackList/addtrack_event), [`change`](/en-US/docs/Web/API/AudioTrackList/change_event)
- This event on [`VideoTrackList`](/en-US/docs/Web/API/VideoTrackList) targets: [`removetrack`](/en-US/docs/Web/API/VideoTrackList/removetrack_event)
- This event on [`MediaStream`](/en-US/docs/Web/API/MediaStream) targets: [`removetrack`](/en-US/docs/Web/API/MediaStream/removetrack_event)
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/audiotracklist | data/mdn-content/files/en-us/web/api/audiotracklist/change_event/index.md | ---
title: "AudioTrackList: change event"
short-title: change
slug: Web/API/AudioTrackList/change_event
page-type: web-api-event
browser-compat: api.AudioTrackList.change_event
---
{{APIRef}}
The `change` event is fired when an audio track is enabled or disabled, for example by changing the track's [`enabled`](/en-US/docs/Web/API/AudioTrack/enabled) property.
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js-nolint
addEventListener("change", (event) => { })
onchange = (event) => { }
```
## Event type
A generic {{domxref("Event")}}.
## Examples
Using `addEventListener()`:
```js
const videoElement = document.querySelector("video");
videoElement.audioTracks.addEventListener("change", (event) => {
console.log(`'${event.type}' event fired`);
});
// changing the value of `enabled` will trigger the `change` event
const toggleTrackButton = document.querySelector(".toggle-track");
toggleTrackButton.addEventListener("click", () => {
const track = videoElement.audioTracks[0];
track.enabled = !track.enabled;
});
```
Using the `onchange` event handler property:
```js
const videoElement = document.querySelector("video");
videoElement.audioTracks.onchange = (event) => {
console.log(`'${event.type}' event fired`);
};
// changing the value of `enabled` will trigger the `change` event
const toggleTrackButton = document.querySelector(".toggle-track");
toggleTrackButton.addEventListener("click", () => {
const track = videoElement.audioTracks[0];
track.enabled = !track.enabled;
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Related events: [`addtrack`](/en-US/docs/Web/API/AudioTrackList/addtrack_event), [`removetrack`](/en-US/docs/Web/API/AudioTrackList/removetrack_event)
- This event on [`VideoTrackList`](/en-US/docs/Web/API/VideoTrackList) targets: [`change`](/en-US/docs/Web/API/VideoTrackList/change_event)
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/audiotracklist | data/mdn-content/files/en-us/web/api/audiotracklist/gettrackbyid/index.md | ---
title: "AudioTrackList: getTrackById() method"
short-title: getTrackById()
slug: Web/API/AudioTrackList/getTrackById
page-type: web-api-instance-method
browser-compat: api.AudioTrackList.getTrackById
---
{{APIRef("HTML DOM")}}
The **{{domxref("AudioTrackList")}}** method
**`getTrackById()`** returns the first
{{domxref("AudioTrack")}} object from the track list whose {{domxref("AudioTrack.id",
"id")}} matches the specified string. This lets you find a specified track if
you know its ID string.
## Syntax
```js-nolint
getTrackById(id)
```
### Parameters
- `id`
- : A string indicating the ID of the track to locate within the track
list.
### Return value
An {{domxref("AudioTrack")}} object indicating the first track found within the
`AudioTrackList` whose `id` matches the specified string. If no
match is found, this method returns `null`.
The tracks are searched in their natural order; that is, in the order defined by the
media resource itself, or, if the resource doesn't define an order, the relative order
in which the tracks are declared by the media resource.
## Examples
This example suggests a hypothetical game in which movies are used as cut-scenes or
other key set pieces within the game. Each movie has one audio track for each character,
as well as one for the music, sound effects, and so forth. This function allows the game
to disable a specific character's audio in order to adjust the movie's performance based
on occurrences within the game; if the character's dialog isn't relevant, it gets left
out. Obviously, that would require some clever graphic design to make work, but it's a
hypothetical game.
```js
function disableCharacter(videoElem, characterName) {
videoElem.audioTracks.getTrackById(characterName).enabled = false;
}
```
This short function gets the {{domxref("AudioTrackList")}} containing the video's audio
tracks using {{domxref("HTMLMediaElement.audioTracks")}}, then calls
`getTrackById()` on it, specifying the character's name. The resulting
track's audio is then disabled by setting its {{domxref("AudioTrack.enabled",
"enabled")}} flag to `false`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcdtlstransport/index.md | ---
title: RTCDtlsTransport
slug: Web/API/RTCDtlsTransport
page-type: web-api-interface
browser-compat: api.RTCDtlsTransport
---
{{APIRef("WebRTC")}}
The **`RTCDtlsTransport`** interface provides access to information about the Datagram Transport Layer Security (**{{Glossary("DTLS")}}**) transport over which a {{domxref("RTCPeerConnection")}}'s {{Glossary("RTP")}} and {{Glossary("RTCP")}} packets are sent and received by its {{domxref("RTCRtpSender")}} and {{domxref("RTCRtpReceiver")}} objects.
A `RTCDtlsTransport` object is also used to provide information about {{Glossary("SCTP")}} packets transmitted and received by a connection's [data channels](/en-US/docs/Web/API/RTCDataChannel).
Features of the DTLS transport include the addition of security to the underlying transport; the `RTCDtlsTransport` interface can be used to obtain information about the underlying transport and the security added to it by the DTLS layer.
{{InheritanceDiagram}}
## Instance properties
_Also inherits properties from {{DOMxRef("EventTarget")}}._
- {{DOMxRef("RTCDtlsTransport.iceTransport", "iceTransport")}} {{ReadOnlyInline}}
- : Returns a reference to the underlying {{DOMxRef("RTCIceTransport")}} object.
- {{DOMxRef("RTCDtlsTransport.state", "state")}} {{ReadOnlyInline}}
- : Returns a string
which describes the underlying Datagram Transport Layer Security (**{{Glossary("DTLS")}}**) transport state.
It can be one of the following values:
`new`, `connecting`, `connected`, `closed`, or `failed`.
## Instance methods
_Also inherits methods from {{DOMxRef("EventTarget")}}._
- {{DOMxRef("RTCDtlsTransport.getRemoteCertificates", "getRemoteCertificates()")}}
- : Returns an array of {{jsxref("ArrayBuffer")}} containing the certificates of the remote peer of the connection.
## Events
- {{DOMxRef("RTCDtlsTransport.error_event", "error")}}
- : Sent when a transport-level error occurs on the {{domxref("RTCPeerConnection")}}.
- {{DOMxRef("RTCDtlsTransport.statechange_event", "statechange")}}
- : Sent when the {{DOMxRef("RTCDtlsTransport.state", "state")}} of the DTLS transport changes.
## Description
### Allocation of DTLS transports
`RTCDtlsTransport` objects are created when an app calls either {{domxref("RTCPeerConnection.setLocalDescription", "setLocalDescription()")}} or {{domxref("RTCPeerConnection.setRemoteDescription", "setRemoteDescription()")}}. The number of DTLS transports created and how they're used depends on the bundling mode used when creating the {{domxref("RTCPeerConnection")}}.
Whether bundling is used depends on what the other endpoint is able to negotiate. All browsers support bundling, so when both endpoints are browsers, you can rest assured that bundling will be used.
Some non-browser legacy endpoints, however, may not support bundle. To be able to negotiate with such endpoints (or to exclude them entirely), the `bundlePolicy` property may be provided when creating the connection. The `bundlePolicy` [lets you control](/en-US/docs/Web/API/RTCPeerConnection#rtcbundlepolicy_enum) how to negotiate with these legacy endpoints. The default policy is `"balanced"`, which provides a balance between performance and compatibility.
For example, to create the connection using the highest level of bundling:
```js
const rtcConfig = {
bundlePolicy: "max-bundle",
};
const pc = new RTCPeerConnection(rtcConfig);
```
[Bundling](https://webrtcstandards.info/sdp-bundle/) lets you use one `RTCDtlsTransport` to carry the data for multiple higher-level transports, such as multiple {{domxref("RTCRtpTransceiver")}}s.
#### When not using BUNDLE
When the connection is created without using BUNDLE, each RTP or RTCP component of each {{domxref("RTCRtpTransceiver")}} has its own `RTCDtlsTransport`; that is, every {{domxref("RTCRtpSender")}} and {{domxref("RTCRtpReceiver")}}, has its own transport, and all {{domxref("RTCDataChannel")}} objects share a transport dedicated to SCTP.
#### When using BUNDLE
When the connection is using BUNDLE, each `RTCDtlsTransport` object represents a group of {{domxref("RTCRtpTransceiver")}} objects. If the connection was created using `max-compat` mode, each transport is responsible for handling all communication for a given type of media (audio, video, or data channel). Thus, a connection with any number of audio and video channels will always have exactly one DTLS transport for audio and one for video communications.
Because transports are established early in the negotiation process, it's likely that it won't be known until after they're created whether or not the remote peer supports bundling. For this reason, you'll sometimes see separate transports created at first, one for each track, then see them get bundled up once it's known that bundling is possible. If your code accesses {{domxref("RTCRtpSender")}}s and/or {{domxref("RTCRtpReceiver")}}s directly, you may encounter situations where they're initially separate, then half or more of them get closed and the senders and receivers updated to refer to the appropriate remaining `RTCDtlsTransport` objects.
### Data channels
{{domxref("RTCDataChannel")}}s use {{Glossary("SCTP")}} to communicate. All of a peer connection's data channels share a single {{domxref("RTCSctpTransport")}}, found in the connection's {{domxref("RTCPeerConnection.sctp", "sctp")}} property.
You can, in turn, identify the `RTCDtlsTransport` used to securely encapsulate the data channels' SCTP communications by looking at the `RTCSctpTransport` object's {{domxref("RTCSctpTransport.transport", "transport")}} property.
## Examples
This example presents a function, `tallySenders()`, which iterates over an `RTCPeerConnection`'s {{domxref("RTCRtpSender")}}s, tallying up how many of them are in various states. The function returns an object containing properties whose values indicate how many senders are in each state.
```js
let pc = new RTCPeerConnection({ bundlePolicy: "max-bundle" });
// …
function tallySenders(pc) {
let results = {
transportMissing: 0,
connectionPending: 0,
connected: 0,
closed: 0,
failed: 0,
unknown: 0,
};
let senderList = pc.getSenders();
senderList.forEach((sender) => {
let transport = sender.transport;
if (!transport) {
results.transportMissing++;
} else {
switch (transport.state) {
case "new":
case "connecting":
results.connectionPending++;
break;
case "connected":
results.connected++;
break;
case "closed":
results.closed++;
break;
case "failed":
results.failed++;
break;
default:
results.unknown++;
break;
}
}
});
return results;
}
```
Note that in this code, the `new` and `connecting` states are being treated as a single `connectionPending` status in the returned object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("RTCRtpSender.transport")}} and {{domxref("RTCRtpReceiver.transport")}}
- {{DOMxRef("RTCSctpTransport.transport")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcdtlstransport | data/mdn-content/files/en-us/web/api/rtcdtlstransport/icetransport/index.md | ---
title: "RTCDtlsTransport: iceTransport property"
short-title: iceTransport
slug: Web/API/RTCDtlsTransport/iceTransport
page-type: web-api-instance-property
browser-compat: api.RTCDtlsTransport.iceTransport
---
{{APIRef("WebRTC")}}
The read-only **{{DOMxRef("RTCDtlsTransport")}}**
property **`iceTransport`** contains a reference
to the underlying {{DOMxRef("RTCIceTransport")}}.
## Value
The underlying {{DOMxRef("RTCIceTransport")}} instance.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("RTCDtlsTransport")}}
- {{DOMxRef("RTCIceTransport")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcdtlstransport | data/mdn-content/files/en-us/web/api/rtcdtlstransport/state/index.md | ---
title: "RTCDtlsTransport: state property"
short-title: state
slug: Web/API/RTCDtlsTransport/state
page-type: web-api-instance-property
browser-compat: api.RTCDtlsTransport.state
---
{{APIRef("WebRTC")}}
The **`state`** read-only property of the
{{DOMxRef("RTCDtlsTransport")}} interface provides information which describes a
Datagram Transport Layer Security (**{{Glossary("DTLS")}}**) transport state.
## Value
A string. Its value is one of the following:
- `new`
- : The initial state when DTLS has not started negotiating yet.
- `connecting`
- : DTLS is in the process of negotiating a secure connection and verifying the remote fingerprint.
- `connected`
- : DTLS has completed negotiation of a secure connection and verified the remote fingerprint.
- `closed`
- : The transport has been closed intentionally as the result of receipt of a
`close_notify` alert, or calling {{DOMxRef("RTCPeerConnection.close()")}}.
- `failed`
- : The transport has failed as the result of an error (such as receipt of an error
alert or failure to validate the remote fingerprint).
## Examples
See [`RTCDtlsTransport`](/en-US/docs/Web/API/RTCDtlsTransport#examples) for example code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
- {{DOMxRef("RTCDtlsTransport")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcdtlstransport | data/mdn-content/files/en-us/web/api/rtcdtlstransport/error_event/index.md | ---
title: "RTCDtlsTransport: error event"
short-title: error
slug: Web/API/RTCDtlsTransport/error_event
page-type: web-api-event
browser-compat: api.RTCDtlsTransport.error_event
---
{{APIRef("WebRTC")}}
An {{domxref("RTCDtlsTransport")}} receives an `error` event when a transport-level error occurs on the {{domxref("RTCPeerConnection")}}.
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("error", (event) => {});
onerror = (event) => {};
```
## Event type
An {{domxref("RTCErrorEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("RTCErrorEvent")}}
## Event properties
_In addition to the standard properties available on the {{domxref("Event")}} interface, `RTCErrorEvent` also includes the following:_
- {{domxref("RTCErrorEvent.error", "error")}} {{ReadOnlyInline}}
- : An {{domxref("RTCError")}} object specifying the error which occurred; this object includes the type of error that occurred, information about where the error occurred (such as which line number in the {{Glossary("SDP")}} or what {{Glossary("SCTP")}} cause code was at issue).
## Description
Transport-level errors will have one of the following values for the specified error's {{domxref("RTCError")}} property {{domxref("RTCError.errorDetail", "errorDetail")}}:
- `dtls-failure`
- : The negotiation of the {{Glossary("DTLS")}} connection failed, or the connection was terminated with a fatal error. The error's {{domxref("DOMException.message", "message")}} contains details about the nature of the error. If a fatal error is _received_, the error object's {{domxref("RTCError.receivedAlert", "receivedAlert")}} property is set to the value of the DTLSL alert received. If, on the other hand, a fatal error was _sent_, the {{domxref("RTCError.sentAlert", "sentAlert")}} is set to the alert's value.
- `fingerprint-failure`
- : The remote certificate for the {{domxref("RTCDtlsTransport")}} didn't match any of the fingerprints listed in the SDP. If the remote peer can't match the local certificate against the provided fingerprints, this error doesn't occur, though this situation may result instead in a `dtls-failure` error.
## Examples
In this example, the {{domxref("RTCDtlsTransport.onerror", "onerror")}} event handler property is used to set the handler for the `error` event.
```js
transport.onerror = (ev) => {
const err = ev.error;
// …
};
```
> **Note:** Since `RTCError` is not one of the legacy errors, the value of {{domxref("DOMException.code", "code")}} is always 0.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/credential/index.md | ---
title: Credential
slug: Web/API/Credential
page-type: web-api-interface
browser-compat: api.Credential
---
{{APIRef("Credential Management API")}}{{securecontext_header}}
The **`Credential`** interface of the [Credential Management API](/en-US/docs/Web/API/Credential_Management_API) provides information about an entity (usually a user) normally as a prerequisite to a trust decision.
`Credential` objects may be of the following types:
- {{domxref("FederatedCredential")}}
- {{domxref("IdentityCredential")}}
- {{domxref("PasswordCredential")}}
- {{domxref("PublicKeyCredential")}}
- {{domxref("OTPCredential")}}
## Instance properties
- {{domxref("Credential.id")}} {{ReadOnlyInline}}
- : Returns a string containing the credential's identifier. This might be any one of a GUID, username, or email address.
- {{domxref("Credential.type")}} {{ReadOnlyInline}}
- : Returns a string containing the credential's type. Valid values are `password`, `federated`, `public-key`, `identity` and `otp`. (For {{domxref("PasswordCredential")}}, {{domxref("FederatedCredential")}}, {{domxref("PublicKeyCredential")}}, {{domxref("IdentityCredential")}} and {{domxref("OTPCredential")}})
## Instance methods
None.
## Examples
```js
const pwdCredential = new PasswordCredential({
id: "example-username", // Username/ID
name: "Carina Anand", // Display name
password: "correct horse battery staple", // Password
});
console.assert(pwdCredential.type === "password");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/credential | data/mdn-content/files/en-us/web/api/credential/id/index.md | ---
title: "Credential: id property"
short-title: id
slug: Web/API/Credential/id
page-type: web-api-instance-property
browser-compat: api.Credential.id
---
{{APIRef("Credential Management API")}}{{SecureContext_Header}}
The **`id`** read-only property of the {{domxref("Credential")}} interface returns a string containing the credential's identifier. This might be a GUID, username, or email address, or some other value, depending on the type of credential.
## Value
A string containing the credential's identifier.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/credential | data/mdn-content/files/en-us/web/api/credential/type/index.md | ---
title: "Credential: type property"
short-title: type
slug: Web/API/Credential/type
page-type: web-api-instance-property
browser-compat: api.Credential.type
---
{{APIRef("Credential Management API")}}{{SecureContext_Header}}
The **`type`** read-only property of the {{domxref("Credential")}} interface returns a string containing the credential's type. Valid values are `password`, `federated`, `public-key`, `identity` and `otp`.
## Value
A string contains a credential's given name.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlallcollection/index.md | ---
title: HTMLAllCollection
slug: Web/API/HTMLAllCollection
page-type: web-api-interface
browser-compat: api.HTMLAllCollection
---
{{APIRef("DOM")}}{{Deprecated_Header}}
The **`HTMLAllCollection`** interface represents a collection of _all_ of the document's elements, accessible by index (like an array) and by the element's [`id`](/en-US/docs/Web/HTML/Global_attributes/id). It is returned by the {{domxref("document.all")}} property.
`HTMLAllCollection` has a very similar shape to {{domxref("HTMLCollection")}}, but there are many subtle behavior differences — for example, `HTMLAllCollection` can be called as a function, and its `item()` method can be called with a string representing an element's `id` or `name` attribute.
## Instance properties
- {{domxref("HTMLAllCollection.length")}} {{ReadOnlyInline}}
- : Returns the number of items in the collection.
## Instance methods
- {{domxref("HTMLAllCollection.item()")}}
- : Returns the element located at the specified offset into the collection, or the element with the specified value for its `id` or `name` attribute. Returns `null` if no element is found.
- {{domxref("HTMLAllCollection.namedItem()")}}
- : Returns the first [element](/en-US/docs/Web/API/Element) in the collection whose [`id`](/en-US/docs/Web/HTML/Global_attributes/id) or `name` attribute match the given string name, or `null` if no element matches.
## Usage in JavaScript
### Indexed access
In addition to the methods above, elements in an `HTMLAllCollection` can be accessed by integer indices and string property names. The HTML `id` attribute may contain `:` and `.` as valid characters, which would necessitate using bracket notation for property access. `collection[i]` is equivalent to `collection.item(i)`, where `i` can be an integer, a string containing an integer, or a string representing an `id`.
### Calling as a function
An `HTMLAllCollection` object is callable. When it's called with no arguments or with `undefined`, it returns `null`. Otherwise, it returns the same value as the {{domxref("HTMLAllCollection/item", "item()")}} method when given the same arguments.
### Special type conversion behavior
For historical reasons, `document.all` is an object that in the following ways behaves like `undefined`:
- It is [loosely equal](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) to `undefined` and `null`.
- It is [falsy](/en-US/docs/Glossary/Falsy) in boolean contexts.
- Its [`typeof`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof) is `"undefined"`.
These special behaviors ensure that code like:
```js
if (document.all) {
// Assume that we are in IE; provide special logic
}
// Assume that we are in a modern browser
```
Will continue to provide modern behavior even if the code is run in a browser that implements `document.all` for compatibility reasons.
However, in all other contexts, `document.all` remains an object. For example:
- It is not [strictly equal](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) to either `undefined` or `null`.
- When used on the left-hand side of the [nullish coalescing operator](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing) (`??`) or the [optional chaining operator](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) (`?.`), it will not cause the expression to short-circuit.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLCollection")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlallcollection | data/mdn-content/files/en-us/web/api/htmlallcollection/length/index.md | ---
title: "HTMLAllCollection: length property"
short-title: length
slug: Web/API/HTMLAllCollection/length
page-type: web-api-instance-property
browser-compat: api.HTMLAllCollection.length
---
{{APIRef("DOM")}}
The **`HTMLAllCollection.length`** property returns the number of items in this {{domxref("HTMLAllCollection")}}.
## Value
An integer value representing the number of items in this `HTMLAllCollection`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLCollection.length")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlallcollection | data/mdn-content/files/en-us/web/api/htmlallcollection/item/index.md | ---
title: "HTMLAllCollection: item() method"
short-title: item()
slug: Web/API/HTMLAllCollection/item
page-type: web-api-instance-method
browser-compat: api.HTMLAllCollection.item
---
{{APIRef("HTML DOM")}}
The **`item()`** method of the {{domxref("HTMLAllCollection")}} interface returns the element located at the specified offset into the collection, or the element with the specified value for its `id` or `name` attribute.
## Syntax
```js-nolint
item(nameOrIndex)
```
### Parameters
- `nameOrIndex`
- : If this parameter is an integer, or a string that can be converted to an integer, then it represents the position of the {{domxref("Element")}} to be returned. Elements appear in an `HTMLAllCollection` in the same order in which they appear in the document's source. If the parameter is a string can't be converted to an integer, it will be interpreted as the `name` or `id` of the element to be returned.
### Return value
If `nameOrIndex` represents an index, `item()` returns the {{domxref("Element")}} at the specified index, or `null` if `nameOrIndex` is less than zero or greater than or equal to the length property. If `nameOrIndex` represents a name, `item()` returns the same value as {{domxref("HTMLAllCollection/namedItem", "namedItem()")}}.
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLCollection.item()")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlallcollection | data/mdn-content/files/en-us/web/api/htmlallcollection/nameditem/index.md | ---
title: "HTMLAllCollection: namedItem() method"
short-title: namedItem()
slug: Web/API/HTMLAllCollection/namedItem
page-type: web-api-instance-method
browser-compat: api.HTMLAllCollection.namedItem
---
{{APIRef("DOM")}}
The **`namedItem()`** method of the {{domxref("HTMLAllCollection")}} interface returns the first {{domxref("Element")}} in the collection whose `id` or `name` attribute matches the specified name, or `null` if no element matches.
## Syntax
```js-nolint
namedItem(name)
```
### Parameters
- `name`
- : A string representing the value of the `id` or `name` attribute of the element we are looking for.
### Return value
The first {{domxref("Element")}} in the {{domxref("HTMLAllCollection")}} matching the `name`, or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), if there are none.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLAllCollection.namedItem()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/csslayerblockrule/index.md | ---
title: CSSLayerBlockRule
slug: Web/API/CSSLayerBlockRule
page-type: web-api-interface
browser-compat: api.CSSLayerBlockRule
---
{{APIRef("CSSOM")}}
The **`CSSLayerBlockRule`** represents a {{cssxref("@layer")}} block rule. It is a grouping at-rule meaning that it can contain other rules, and is associated to a given cascade layer, identified by its _name_.
{{InheritanceDiagram}}
## Instance properties
_Also inherits properties from its parent interface, {{DOMxRef("CSSGroupingRule")}}._
- {{DOMxRef("CSSLayerBlockRule.name")}} {{ReadOnlyInline}}
- A string containing the name of the associated cascade layer.
## Instance methods
_Inherits methods from its parent interface, {{DOMxRef("CSSGroupingRule")}}._
## Examples
### HTML
```html
<p>I am displayed in <code>color: rebeccapurple</code>.</p>
```
### CSS
```css
@layer special {
p {
color: rebeccapurple;
}
}
```
### JavaScript
```js
const item = document.getElementsByTagName("p")[0];
const rules = document.styleSheets[1].cssRules;
// Note that stylesheet #1 is the stylesheet associated with this embedded example,
// while stylesheet #0 is the stylesheet associated with the whole MDN page
const layer = rules[0]; // A CSSLayerBlockRule
item.textContent = `The CSSLayerBlockRule is for the "${layer.name}" layer`;
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{cssxref("@layer")}}
- {{DOMxRef("CSSLayerStatementRule")}}
- [Learn CSS cascade layers](/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers)
| 0 |
data/mdn-content/files/en-us/web/api/csslayerblockrule | data/mdn-content/files/en-us/web/api/csslayerblockrule/name/index.md | ---
title: "CSSLayerBlockRule: name property"
short-title: name
slug: Web/API/CSSLayerBlockRule/name
page-type: web-api-instance-property
browser-compat: api.CSSLayerBlockRule.name
---
{{APIRef("CSSOM")}}
The read-only **`name`** property of the {{domxref("CSSLayerBlockRule")}} interface represents the name of the associated cascade layer.
## Value
A string containing the name of the layer, or `""` if the layer is anonymous.
## Examples
### HTML
```html
<output></output> <output></output>
```
### CSS
```css
output {
display: block;
}
@layer special {
div {
color: rebeccapurple;
}
}
@layer {
div {
color: black;
}
}
```
### JavaScript
```js
const item1 = document.getElementsByTagName("output")[0];
const item2 = document.getElementsByTagName("output")[1];
const rules = document.styleSheets[1].cssRules;
// Note that stylesheet #1 is the stylesheet associated with this embedded example,
// while stylesheet #0 is the stylesheet associated with the whole MDN page
const layer = rules[1]; // A CSSLayerBlockRule
const anonymous = rules[2]; // An anonymous CSSLayerBlockRule
item1.textContent = `The first CSSLayerBlockRule defines the "${layer.name}" layer.`;
item2.textContent = `A second CSSLayerBlockRule defines a layer with the following name: "${anonymous.name}".`;
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The statement declaration of an {{cssxref("@layer")}} is represented by a {{domxref("CSSLayerStatementRule")}}.
- How to [create named cascade layers](/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers#creating_cascade_layers) in CSS.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/stereopannernode/index.md | ---
title: StereoPannerNode
slug: Web/API/StereoPannerNode
page-type: web-api-interface
browser-compat: api.StereoPannerNode
---
{{APIRef("Web Audio API")}}
The `StereoPannerNode` interface of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) represents a simple stereo panner node that can be used to pan an audio stream left or right. It is an {{domxref("AudioNode")}} audio-processing module that positions an incoming audio stream in a stereo image using a low-cost equal-power [panning algorithm](https://webaudio.github.io/web-audio-api/#panning-algorithm).
The {{domxref("StereoPannerNode.pan", "pan")}} property takes a unitless value between `-1` (full left pan) and `1` (full right pan). This interface was introduced as a much simpler way to apply a simple panning effect than having to use a full {{domxref("PannerNode")}}.

{{InheritanceDiagram}}
<table class="properties">
<tbody>
<tr>
<th scope="row">Number of inputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Number of outputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Channel count mode</th>
<td><code>"clamped-max"</code></td>
</tr>
<tr>
<th scope="row">Channel count</th>
<td><code>2</code></td>
</tr>
<tr>
<th scope="row">Channel interpretation</th>
<td><code>"speakers"</code></td>
</tr>
</tbody>
</table>
## Constructor
- {{domxref("StereoPannerNode.StereoPannerNode", "StereoPannerNode()")}}
- : Creates a new instance of a `StereoPannerNode` object.
## Instance properties
_Inherits properties from its parent, {{domxref("AudioNode")}}_.
- {{domxref("StereoPannerNode.pan")}} {{ReadOnlyInline}}
- : An [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} representing the amount of panning to apply.
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("AudioNode")}}_.
## Example
See [`BaseAudioContext.createStereoPanner()`](/en-US/docs/Web/API/BaseAudioContext/createStereoPanner#examples) for example code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/stereopannernode | data/mdn-content/files/en-us/web/api/stereopannernode/pan/index.md | ---
title: "StereoPannerNode: pan property"
short-title: pan
slug: Web/API/StereoPannerNode/pan
page-type: web-api-instance-property
browser-compat: api.StereoPannerNode.pan
---
{{APIRef("Web Audio API")}}
The `pan` property of the {{ domxref("StereoPannerNode") }} interface is an [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} representing the amount of panning to apply. The value can range between `-1` (full left pan) and `1` (full right pan).
## Value
An [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} containing the panning to apply.
> **Note:** Though the `AudioParam` returned is read-only, the value it represents is not.
## Examples
See [`BaseAudioContext.createStereoPanner()`](/en-US/docs/Web/API/BaseAudioContext/createStereoPanner#examples) for example code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/stereopannernode | data/mdn-content/files/en-us/web/api/stereopannernode/stereopannernode/index.md | ---
title: "StereoPannerNode: StereoPannerNode() constructor"
short-title: StereoPannerNode()
slug: Web/API/StereoPannerNode/StereoPannerNode
page-type: web-api-constructor
browser-compat: api.StereoPannerNode.StereoPannerNode
---
{{APIRef("Web Audio API")}}
The **`StereoPannerNode()`** constructor of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) creates a new {{domxref("StereoPannerNode")}} object which is an {{domxref("AudioNode")}} that represents a simple stereo panner node that can be used to pan an audio stream left or right.
## Syntax
```js-nolint
new StereoPannerNode(context, options)
```
### Parameters
- `context`
- : A reference to an {{domxref("AudioContext")}}.
- `options` {{optional_inline}}
- : Options are as follows:
- `pan`
- : A floating point number in the range \[-1,1] indicating the position of an {{domxref("AudioNode")}} in an output image.
The value -1 represents full left and 1 represents full right.
The default value is `0`.
- `channelCount`
- : Represents an integer used to determine how many channels are used when [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) connections to any inputs to the node.
(See {{domxref("AudioNode.channelCount")}} for more information.)
Its usage and precise definition depend on the value of `channelCountMode`.
- `channelCountMode`
- : Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.
(See {{domxref("AudioNode.channelCountMode")}} for more information including default values.)
- `channelInterpretation`
- : Represents an enumerated value describing the meaning of the channels.
This interpretation will define how audio [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) will happen.
The possible values are `"speakers"` or `"discrete"`.
(See {{domxref("AudioNode.channelCountMode")}} for more information including default values.)
### Return value
A new {{domxref("StereoPannerNode")}} object instance.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediarecordererrorevent/index.md | ---
title: MediaRecorderErrorEvent
slug: Web/API/MediaRecorderErrorEvent
page-type: web-api-interface
status:
- deprecated
- non-standard
browser-compat: api.MediaRecorderErrorEvent
---
{{APIRef("MediaStream Recording")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`MediaRecorderErrorEvent`** interface represents errors returned by the [MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API). It is an {{domxref("Event")}} object that encapsulates a reference to a {{domxref("DOMException")}} describing the error that occurred.
{{InheritanceDiagram}}
## Constructor
- {{domxref("MediaRecorderErrorEvent.MediaRecorderErrorEvent", "MediaStreamRecorderEvent()")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Creates and returns a new `MediaRecorderErrorEvent` event object with the given parameters.
## Instance properties
_Inherits properties from its parent interface, {{domxref("Event")}}_.
- {{domxref("MediaRecorderErrorEvent.error", "error")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : A {{domxref("DOMException")}} containing information about the error that occurred.
## Instance methods
_Inherits methods from its parent interface, {{domxref("Event")}}_.
## Specifications
This feature is no longer part of any specification.
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediarecordererrorevent | data/mdn-content/files/en-us/web/api/mediarecordererrorevent/error/index.md | ---
title: "MediaRecorderErrorEvent: error property"
short-title: error
slug: Web/API/MediaRecorderErrorEvent/error
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.MediaRecorderErrorEvent.error
---
{{APIRef("MediaStream Recording")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`error`** read-only property of the
{{domxref("MediaRecorderErrorEvent")}} interface is a
{{domxref("DOMException")}} object providing details about the exception that was thrown
by a {{domxref("MediaRecorder")}} instance.
When a `MediaRecorderErrorEvent` occurs, you can determine to some extent
what went wrong by examining the `error` property within the
`MediaRecorderErrorEvent` received by the `MediaRecorder`'s
{{domxref("MediaRecorder/error_event", "error")}} event handler, {{domxref("MediaRecorder/error_event", "onerror")}}.
## Value
A {{domxref("DOMException")}} describing the error represented by the event. The
error's {{domxref("DOMException.name", "name")}} property's value may be any exception
that makes sense during the handling of media recording, including these specifically
identified by the specification. The descriptions here are generic ones; you'll find
more specific ones to various scenarios in which they may occur in the corresponding
method references.
- `InvalidStateError`
- : An operation was attempted in a context in which it isn't allowed, or a request has
been made on an object that's deleted or removed.
- `NotSupportedError`
- : A `MediaRecorder` couldn't be created because the specified options
weren't valid. The `message` attribute should provide additional
information, if it exists.
- `SecurityError`
- : The {{domxref("MediaStream")}} is configured to disallow recording. This may be the
case, for example, with sources obtained using {{domxref("MediaDevices.getUserMedia",
"getUserMedia()")}} when the user denies permission to use an input device.
- `InvalidModificationError`
- : The number of tracks on the stream being recorded has changed. You can't add or
remove tracks while recording media.
- `UnknownError`
- : A non-security related error occurred that cannot otherwise be categorized.
Recording stops, the `MediaRecorder`'s {{domxref("MediaRecorder.state",
"state")}} becomes `inactive`, one last {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event is
sent to the `MediaRecorder` with the remaining received data, and finally a
{{domxref("MediaRecorder/stop_event", "stop")}} event is sent.
## Examples
### Basic error-handling example
This function creates and returns a `MediaRecorder` for a given
{{domxref("MediaStream")}}, configured to buffer data into an array and to watch for
errors.
```js
function recordStream(stream) {
let recorder = null;
let bufferList = [];
try {
recorder = new MediaRecorder(stream);
} catch (err) {
/* exception while trying to create the recorder; handle that */
}
recorder.ondataavailable = (event) => {
bufferList.push(event.data);
};
recorder.onerror = (event) => {
console.error(`Error: ${event.error}`);
};
recorder.start(100); /* 100ms time slices per buffer */
return recorder;
}
```
## Specifications
This feature is no longer part of any specification, and longer on track to become standard.
## Browser compatibility
{{Compat}}
## See also
- [MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API)
- [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API)
| 0 |
data/mdn-content/files/en-us/web/api/mediarecordererrorevent | data/mdn-content/files/en-us/web/api/mediarecordererrorevent/mediarecordererrorevent/index.md | ---
title: "MediaRecorderErrorEvent: MediaRecorderErrorEvent() constructor"
short-title: MediaRecorderErrorEvent()
slug: Web/API/MediaRecorderErrorEvent/MediaRecorderErrorEvent
page-type: web-api-constructor
status:
- deprecated
- non-standard
browser-compat: api.MediaRecorderErrorEvent.MediaRecorderErrorEvent
---
{{APIRef("MediaStream Recording")}}{{Deprecated_Header}}{{Non-standard_Header}}
The
**`MediaRecorderErrorEvent()`** constructor creates a new {{domxref("MediaRecorderErrorEvent")}} object
that represents an error that occurred during the recording of media
by the [MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API).
> **Note:** In general, you won't create these yourself; they are delivered to your
> implementation of {{domxref("MediaRecorder.error_event", "onerror")}} when errors occur while
> recording media.
## Syntax
```js-nolint
new MediaRecorderErrorEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `error`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `error`
- : A {{domxref("DOMException")}} that describes the error that occurred. This
object's {{domxref("DOMException.name", "name")}} property should indicate the
name of the error that occurred. The other fields may or may not be present.
> **Note:** Some {{Glossary("user agent", "user agents")}} add to the `error` object
> other properties that provide information such as stack dumps, the name of the
> JavaScript file and the line number where the error occurred, and other debugging
> aids, but you should not rely on this information in a production environment.
### Return value
A new {{domxref("MediaRecorderErrorEvent")}} object.
## Specifications
This feature is no longer part of any specification, and longer on track to become standard.
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/request/index.md | ---
title: Request
slug: Web/API/Request
page-type: web-api-interface
browser-compat: api.Request
---
{{APIRef("Fetch API")}}
The **`Request`** interface of the [Fetch API](/en-US/docs/Web/API/Fetch_API) represents a resource request.
You can create a new `Request` object using the {{domxref("Request.Request","Request()")}} constructor, but you are more likely to encounter a `Request` object being returned as the result of another API operation, such as a service worker {{domxref("FetchEvent.request")}}.
## Constructor
- {{domxref("Request.Request","Request()")}}
- : Creates a new `Request` object.
## Instance properties
- {{domxref("Request.body")}} {{ReadOnlyInline}}
- : A {{domxref("ReadableStream")}} of the body contents.
- {{domxref("Request.bodyUsed")}} {{ReadOnlyInline}}
- : Stores `true` or `false` to indicate whether or not the body has been used in a request yet.
- {{domxref("Request.cache")}} {{ReadOnlyInline}}
- : Contains the cache mode of the request (e.g., `default`, `reload`, `no-cache`).
- {{domxref("Request.credentials")}} {{ReadOnlyInline}}
- : Contains the credentials of the request (e.g., `omit`, `same-origin`, `include`). The default is `same-origin`.
- {{domxref("Request.destination")}} {{ReadOnlyInline}}
- : A string describing the type of content being requested.
- {{domxref("Request.headers")}} {{ReadOnlyInline}}
- : Contains the associated {{domxref("Headers")}} object of the request.
- {{domxref("Request.integrity")}} {{ReadOnlyInline}}
- : Contains the [subresource integrity](/en-US/docs/Web/Security/Subresource_Integrity) value of the request (e.g., `sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=`).
- {{domxref("Request.method")}} {{ReadOnlyInline}}
- : Contains the request's method (`GET`, `POST`, etc.)
- {{domxref("Request.mode")}} {{ReadOnlyInline}}
- : Contains the mode of the request (e.g., `cors`, `no-cors`, `same-origin`, `navigate`.)
- {{domxref("Request.redirect")}} {{ReadOnlyInline}}
- : Contains the mode for how redirects are handled. It may be one of `follow`, `error`, or `manual`.
- {{domxref("Request.referrer")}} {{ReadOnlyInline}}
- : Contains the referrer of the request (e.g., `client`).
- {{domxref("Request.referrerPolicy")}} {{ReadOnlyInline}}
- : Contains the referrer policy of the request (e.g., `no-referrer`).
- {{domxref("Request.signal")}} {{ReadOnlyInline}}
- : Returns the {{domxref("AbortSignal")}} associated with the request
- {{domxref("Request.url")}} {{ReadOnlyInline}}
- : Contains the URL of the request.
## Instance methods
- {{domxref("Request.arrayBuffer()")}}
- : Returns a promise that resolves with an {{jsxref("ArrayBuffer")}} representation of the request body.
- {{domxref("Request.blob()")}}
- : Returns a promise that resolves with a {{domxref("Blob")}} representation of the request body.
- {{domxref("Request.clone()")}}
- : Creates a copy of the current `Request` object.
- {{domxref("Request.formData()")}}
- : Returns a promise that resolves with a {{domxref("FormData")}} representation of the request body.
- {{domxref("Request.json()")}}
- : Returns a promise that resolves with the result of parsing the request body as {{JSxRef("JSON")}}.
- {{domxref("Request.text()")}}
- : Returns a promise that resolves with a text representation of the request body.
> **Note:** The request body functions can be run only once; subsequent calls will reject with TypeError showing that the body stream has already used.
## Examples
In the following snippet, we create a new request using the `Request()` constructor (for an image file in the same directory as the script), then return some property values of the request:
```js
const request = new Request("https://www.mozilla.org/favicon.ico");
const url = request.url;
const method = request.method;
const credentials = request.credentials;
```
You could then fetch this request by passing the `Request` object in as a parameter to a {{domxref("fetch()")}} call, for example:
```js
fetch(request)
.then((response) => response.blob())
.then((blob) => {
image.src = URL.createObjectURL(blob);
});
```
In the following snippet, we create a new request using the `Request()` constructor with some initial data and body content for an API request which need a body payload:
```js
const request = new Request("https://example.com", {
method: "POST",
body: '{"foo": "bar"}',
});
const url = request.url;
const method = request.method;
const credentials = request.credentials;
const bodyUsed = request.bodyUsed;
```
> **Note:** The body can only be a {{domxref("Blob")}}, an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, a {{jsxref("DataView")}}, a {{domxref("FormData")}}, a {{domxref("URLSearchParams")}}, a {{domxref("ReadableStream")}}, or a {{jsxref("String")}} object, as well as a string literal, so for adding a JSON object to the payload you need to stringify that object.
You could then fetch this API request by passing the `Request` object in as a parameter to a {{domxref("fetch()")}} call, for example and get the response:
```js
fetch(request)
.then((response) => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("Something went wrong on API server!");
}
})
.then((response) => {
console.debug(response);
// …
})
.catch((error) => {
console.error(error);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/clone/index.md | ---
title: "Request: clone() method"
short-title: clone()
slug: Web/API/Request/clone
page-type: web-api-instance-method
browser-compat: api.Request.clone
---
{{APIRef("Fetch API")}}
The **`clone()`** method of the {{domxref("Request")}} interface creates a copy of the current `Request` object.
Like the underlying {{domxref("ReadableStream.tee")}} api,
the {{domxref("Request.body", "body")}} of a cloned `Response`
will signal backpressure at the rate of the _faster_ consumer of the two bodies,
and unread data is enqueued internally on the slower consumed `body`
without any limit or backpressure.
Beware when you construct a `Request` from a stream and then `clone` it.
`clone()` throws a {{jsxref("TypeError")}} if the request body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.)
If you intend to modify the request, you may prefer the {{domxref("Request")}} constructor.
## Syntax
```js-nolint
clone()
```
### Parameters
None.
### Return value
A {{domxref("Request")}} object, which is an exact copy of the `Request` that `clone()` was called on.
## Examples
In the following snippet, we create a new request using the {{domxref("Request.Request", "Request()")}} constructor (for an image file in the same directory as the script), then clone the request.
```js
const myRequest = new Request("flowers.jpg");
const newRequest = myRequest.clone(); // a copy of the request is now stored in newRequest
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/body/index.md | ---
title: "Request: body property"
short-title: body
slug: Web/API/Request/body
page-type: web-api-instance-property
browser-compat: api.Request.body
---
{{APIRef("Fetch API")}}
The read-only **`body`** property of the {{domxref("Request")}}
interface contains a {{domxref("ReadableStream")}} with the body contents
that have been added to the request. Note that a request using the
`GET` or `HEAD` method cannot have a body
and `null` is returned in these cases.
## Value
A {{domxref("ReadableStream")}} or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null).
## Examples
```js
const request = new Request("/myEndpoint", {
method: "POST",
body: "Hello world",
});
request.body; // ReadableStream
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Request.bodyUsed")}}
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/mode/index.md | ---
title: "Request: mode property"
short-title: mode
slug: Web/API/Request/mode
page-type: web-api-instance-property
browser-compat: api.Request.mode
---
{{APIRef("Fetch API")}}
The **`mode`** read-only property of the {{domxref("Request")}}
interface contains the mode of the request (e.g., `cors`,
`no-cors`, `same-origin`, `navigate` or `websocket`.) This is used
to determine if cross-origin requests lead to valid responses, and which properties of the response are readable.
## Value
- A `RequestMode` value.
- : The associated _mode_, available values of which are:
- `same-origin`
- : If a request is made to another origin with this mode
set, the result is an error. You could use this to ensure that a request is always
being made to your origin.
- `no-cors`
- : Prevents the method from being anything other than `HEAD`, `GET` or `POST`, and the headers from being anything other than {{Glossary("CORS-safelisted request header", "CORS-safelisted request headers")}}.
If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are {{Glossary("CORS-safelisted request header", "CORS-safelisted request headers")}}.
In addition, JavaScript may not access any properties of the resulting {{domxref("Response")}}.
This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.
- `cors`
- : Allows cross-origin requests, for example to access various
APIs offered by 3rd party vendors. These are expected to adhere to the [CORS protocol](/en-US/docs/Web/HTTP/CORS). Only a [limited set](https://fetch.spec.whatwg.org/#concept-filtered-response-cors) of headers are exposed in the {{domxref("Response")}}, but the body is
readable.
- `navigate`
- : A mode for supporting navigation. The `navigate` value is intended to be used only by HTML navigation. A navigate request is created only while navigating between documents.
- `websocket`
- : A special mode used only when establishing a [WebSocket](/en-US/docs/Web/API/WebSockets_API) connection.
### Default mode
Requests can be initiated in a variety of ways, and the mode for a request depends on
the particular means by which it was initiated.
For example, when a `Request` object is created using the
{{domxref("Request.Request", "Request()")}} constructor, the value of the `mode` property
for that `Request` is set to `cors`.
However, for requests created other than by the {{domxref("Request.Request", "Request()")}}
constructor, `no-cors` is typically used as the mode; for example, for
embedded resources where the request is initiated from markup, unless the
[`crossorigin`](/en-US/docs/Web/HTML/Attributes/crossorigin)
attribute is present, the request is in most cases made using the `no-cors`
mode — that is, for the {{HTMLElement("link")}} or {{HTMLElement("script")}} elements
(except when used with modules), or {{HTMLElement("img")}}, {{HTMLElement("audio")}},
{{HTMLElement("video")}}, {{HTMLElement("object")}}, {{HTMLElement("embed")}}, or
{{HTMLElement("iframe")}} elements.
## Examples
In the following snippet, we create a new request using the
{{domxref("Request.Request", "Request()")}} constructor (for an image file in the same directory as
the script), then save the request mode in a variable:
```js
const myRequest = new Request("flowers.jpg");
const myMode = myRequest.mode; // returns "cors" by default
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/json/index.md | ---
title: "Request: json() method"
short-title: json()
slug: Web/API/Request/json
page-type: web-api-instance-method
browser-compat: api.Request.json
---
{{APIRef("Fetch API")}}
The **`json()`** method of the {{domxref("Request")}} interface
reads the request body and returns it as a promise that resolves with the result of parsing the body text as {{JSxRef("JSON")}}.
Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.
## Syntax
```js-nolint
json()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves to a JavaScript object. This object could be
anything that can be represented by JSON — an object, an array, a string, a number…
## Examples
```js
const obj = { hello: "world" };
const request = new Request("/myEndpoint", {
method: "POST",
body: JSON.stringify(obj),
});
request.json().then((data) => {
// do something with the data sent in the request
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Response.json()")}}
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/signal/index.md | ---
title: "Request: signal property"
short-title: signal
slug: Web/API/Request/signal
page-type: web-api-instance-property
browser-compat: api.Request.signal
---
{{APIRef("Fetch API")}}
The read-only **`signal`** property of the {{DOMxRef("Request")}} interface returns the {{domxref("AbortSignal")}} associated with the request.
## Value
An {{DOMxRef("AbortSignal")}} object.
## Examples
```js
// Create a new abort controller
const controller = new AbortController();
// Create a request with this controller's AbortSignal object
const req = new Request("/", { signal: controller.signal });
// Add an event handler logging a message in case of abort
req.signal.addEventListener("abort", () => {
console.log("abort");
});
// In case of abort, log the AbortSignal reason, if any
fetch(req).catch(() => {
if (signal.aborted) {
if (signal.reason) {
console.log(`Request aborted with reason: ${signal.reason}`);
} else {
console.log("Request aborted but no reason was given.");
}
} else {
console.log("Request not aborted, but terminated abnormally.");
}
});
// Actually abort the request
controller.abort();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/method/index.md | ---
title: "Request: method property"
short-title: method
slug: Web/API/Request/method
page-type: web-api-instance-property
browser-compat: api.Request.method
---
{{APIRef("Fetch API")}}
The **`method`** read-only property of the
{{domxref("Request")}} interface contains the request's method (`GET`,
`POST`, etc.)
## Value
A {{jsxref("String")}} indicating the method of the request.
## Examples
In the following snippet, we create a new request using the
{{domxref("Request.Request", "Request()")}} constructor (for an image file in the same directory as
the script), then save the method of the request in a variable:
```js
const myRequest = new Request("flowers.jpg");
const myMethod = myRequest.method; // GET
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/referrer/index.md | ---
title: "Request: referrer property"
short-title: referrer
slug: Web/API/Request/referrer
page-type: web-api-instance-property
browser-compat: api.Request.referrer
---
{{APIRef("Fetch API")}}
The **`referrer`** read-only property of the
{{domxref("Request")}} interface is set by the user agent to be the referrer of the
Request. (e.g., `client`, `no-referrer`, or a URL.)
> **Note:** If `referrer`'s value is `no-referrer`,
> it returns an empty string.
## Value
A string representing the request's referrer.
## Examples
In the following snippet, we create a new request using the
{{domxref("Request.Request", "Request()")}} constructor (for an image file in the same directory as
the script), then save the request referrer in a variable:
```js
const myRequest = new Request("flowers.jpg");
const myReferrer = myRequest.referrer; // returns "about:client" by default
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/cache/index.md | ---
title: "Request: cache property"
short-title: cache
slug: Web/API/Request/cache
page-type: web-api-instance-property
browser-compat: api.Request.cache
---
{{APIRef("Fetch API")}}
The **`cache`** read-only property of the {{domxref("Request")}} interface contains the cache mode of the request. It controls how the request will interact with the browser's [HTTP cache](/en-US/docs/Web/HTTP/Caching).
## Value
A `RequestCache` value. The available values are:
- `default` — The browser looks for a matching request in its HTTP cache.
- If there is a match and it is [fresh](/en-US/docs/Web/HTTP/Caching#fresh_and_stale_based_on_age), it will be returned from the cache.
- If there is a match but it is [stale](/en-US/docs/Web/HTTP/Caching#fresh_and_stale_based_on_age), the browser will make a [conditional request](/en-US/docs/Web/HTTP/Conditional_requests) to the remote server. If the server indicates that the resource has not changed, it will be returned from the cache. Otherwise the resource will be downloaded from the server and the cache will be updated.
- If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource.
- `no-store` — The browser fetches the resource from the remote server without first looking in the cache, _and will not_ update the cache with the downloaded resource.
- `reload` — The browser fetches the resource from the remote server without first looking in the cache, _but then will_ update the cache with the downloaded resource.
- `no-cache` — The browser looks for a matching request in its HTTP cache.
- If there is a match, _fresh or stale,_ the browser will make a [conditional request](/en-US/docs/Web/HTTP/Conditional_requests) to the remote server. If the server indicates that the resource has not changed, it will be returned from the cache. Otherwise the resource will be downloaded from the server and the cache will be updated.
- If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource.
- `force-cache` — The browser looks for a matching request in its HTTP cache.
- If there is a match, _fresh or stale_, it will be returned from the cache.
- If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource.
- `only-if-cached` — The browser looks for a matching request in its HTTP cache. {{experimental_inline}}
- If there is a match, _fresh or stale_, it will be returned from the cache.
- If there is no match, the browser will respond with a [504 Gateway timeout](/en-US/docs/Web/HTTP/Status/504) status.
The `"only-if-cached"` mode can only be used if the request's [`mode`](/en-US/docs/Web/API/Request/mode) is `"same-origin"`. Cached redirects will be followed if the request's `redirect` property is `"follow"` and the redirects do not violate the `"same-origin"` mode.
## Examples
```js
// Download a resource with cache busting, to bypass the cache
// completely.
fetch("some.json", { cache: "no-store" }).then((response) => {
/* consume the response */
});
// Download a resource with cache busting, but update the HTTP
// cache with the downloaded resource.
fetch("some.json", { cache: "reload" }).then((response) => {
/* consume the response */
});
// Download a resource with cache busting when dealing with a
// properly configured server that will send the correct ETag
// and Date headers and properly handle If-Modified-Since and
// If-None-Match request headers, therefore we can rely on the
// validation to guarantee a fresh response.
fetch("some.json", { cache: "no-cache" }).then((response) => {
/* consume the response */
});
// Download a resource with economics in mind! Prefer a cached
// albeit stale response to conserve as much bandwidth as possible.
fetch("some.json", { cache: "force-cache" }).then((response) => {
/* consume the response */
});
// Naive stale-while-revalidate client-level implementation.
// Prefer a cached albeit stale response; but update if it's too old.
// AbortController and signal to allow better memory cleaning.
// In reality; this would be a function that takes a path and a
// reference to the controller since it would need to change the value
let controller = new AbortController();
fetch("some.json", {
cache: "only-if-cached",
mode: "same-origin",
signal: controller.signal,
})
.catch((e) =>
e instanceof TypeError && e.message === "Failed to fetch"
? { status: 504 } // Workaround for chrome; which fails with a TypeError
: Promise.reject(e),
)
.then((res) => {
if (res.status === 504) {
controller.abort();
controller = new AbortController();
return fetch("some.json", {
cache: "force-cache",
mode: "same-origin",
signal: controller.signal,
});
}
const date = res.headers.get("date"),
dt = date ? new Date(date).getTime() : 0;
if (dt < Date.now() - 86_400_000) {
// if older than 24 hours
controller.abort();
controller = new AbortController();
return fetch("some.json", {
cache: "reload",
mode: "same-origin",
signal: controller.signal,
});
}
// Other possible conditions
if (dt < Date.now() - 300_000)
// If it's older than 5 minutes
fetch("some.json", { cache: "no-cache", mode: "same-origin" }); // no cancellation or return value.
return res;
})
.then((response) => {
/* consume the (possibly stale) response */
})
.catch((error) => {
/* Can be an AbortError/DOMException or a TypeError */
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/blob/index.md | ---
title: "Request: blob() method"
short-title: blob()
slug: Web/API/Request/blob
page-type: web-api-instance-method
browser-compat: api.Request.blob
---
{{APIRef("Fetch API")}}
The **`blob()`** method of the {{domxref("Request")}} interface
reads the request body and returns it as a promise that resolves with a {{domxref("Blob")}}.
## Syntax
```js-nolint
blob()
```
### Parameters
None.
### Return value
A promise that resolves with a {{domxref("Blob")}}.
## Examples
```js
const obj = { hello: "world" };
const myBlob = new Blob([JSON.stringify(obj, null, 2)], {
type: "application/json",
});
const request = new Request("/myEndpoint", {
method: "POST",
body: myBlob,
});
request.blob().then((myBlob) => {
// do something with the blob sent in the request
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Response.blob()")}}
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/redirect/index.md | ---
title: "Request: redirect property"
short-title: redirect
slug: Web/API/Request/redirect
page-type: web-api-instance-property
browser-compat: api.Request.redirect
---
{{APIRef("Fetch API")}}
The **`redirect`** read-only property of the {{domxref("Request")}} interface contains the mode for how redirects are handled.
## Value
A `RequestRedirect` enum value, which can be one the following strings:
- `follow`
- `error`
- `manual`
If not specified when the request is created, it takes the default value of `follow`.
## Examples
In the following snippet, we create a new request using the {{domxref("Request.Request", "Request()")}} constructor (for an image file in the same directory as the script), then save the request `redirect` value in a variable:
```js
const myRequest = new Request("flowers.jpg");
const myCred = myRequest.redirect;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/destination/index.md | ---
title: "Request: destination property"
short-title: destination
slug: Web/API/Request/destination
page-type: web-api-instance-property
browser-compat: api.Request.destination
---
{{APIRef("Fetch API")}}
The **`destination`** read-only
property of the **{{domxref("Request")}}** interface returns a string
describing the type of content being requested.
The string must be one of the `audio`, `audioworklet`,
`document`, `embed`, `font`, `frame`,
`iframe`, `image`, `manifest`, `object`,
`paintworklet`, `report`, `script`, `sharedworker`,
`style`, `track`, `video`, `worker`
or `xslt` strings, or the empty string, which is the default value.
The `destination` is used by the {{Glossary("user agent")}} to, for example,
help determine which set of rules to follow for CORS purposes, or how to navigate any
complicated code paths that affect how specific types of request get handled.
These destinations vary substantially in how they operate. Some are data receptacles,
where the received data is stored for processing later. Others are script-based, in
which case the received data is delivered to a script by calling it and passing the data
along. Script-based destinations include {{HTMLElement("script")}} elements, as well as
any of the {{domxref("Worklet")}}-based destinations
(including subclasses like {{domxref("AudioWorklet")}}), and the
{{domxref("Worker")}}-based destinations, including {{domxref("ServiceWorker")}}
and {{domxref("SharedWorker")}}.
## Value
A string which indicates the type of content the request is asking for. This type is much broader than the usual document type values (such as `"document"` or `"manifest"`), and may include contextual cues such as `"image"` or `"worker"` or `"audioworklet"`.
Possible values are:
- `""`
- : The empty string is the default value, and is used for destinations that do not have their own value. This is the value when requests are made using the following APIs (among others):
- [`<a ping>`](/en-US/docs/Web/HTML/Element/a#ping)
- [`<area ping>`](/en-US/docs/Web/HTML/Element/area#ping)
- {{domxref("Cache")}}
- {{domxref("EventSource")}}
- {{domxref("fetch()")}}
- {{domxref("navigator.sendBeacon()")}}
- {{domxref("WebSocket")}}
- {{domxref("XMLHttpRequest")}}
- `"audio"`
- : The target is audio data.
- `"audioworklet"`
- : The target is data being fetched for use by an audio worklet.
- `"document"`
- : The target is a document (HTML or XML).
- `"embed"`
- : The target is embedded content.
- `"font"`
- : The target is a font.
- `"image"`
- : The target is an image.
- `"manifest"`
- : The target is a manifest.
- `"object"`
- : The target is an object.
- `"paintworklet"`
- : The target is a paint worklet.
- `"report"`
- : The target is a report.
- `"script"`
- : The target is a script.
- `"serviceworker"`
- : The target is a service worker.
- `"sharedworker"`
- : The target is a shared worker.
- `"style"`
- : The target is a style
- `"track"`
- : The target is an HTML {{HTMLElement("track")}}.
- `"video"`
- : The target is video data.
- `"worker"`
- : The target is a worker.
- `"xslt"`
- : The target is an XSLT transform.
## Examples
In the following snippet, we create a new request using the
{{domxref("Request.Request", "Request()")}} constructor (for an image file in the same
directory as the script), then save the request's destination:
```js
const myRequest = new Request("flowers.jpg");
const myDestination = myRequest.destination; // returns the empty string by default
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/arraybuffer/index.md | ---
title: "Request: arrayBuffer() method"
short-title: arrayBuffer()
slug: Web/API/Request/arrayBuffer
page-type: web-api-instance-method
browser-compat: api.Request.arrayBuffer
---
{{APIRef("Fetch API")}}
The **`arrayBuffer()`** method of the {{domxref("Request")}} interface
reads the request body and returns it as a promise that resolves with an {{jsxref("ArrayBuffer")}}.
## Syntax
```js-nolint
arrayBuffer()
```
### Parameters
None.
### Return value
A promise that resolves with an {{jsxref("ArrayBuffer")}}.
## Examples
```js
const myArray = new Uint8Array(10);
const request = new Request("/myEndpoint", {
method: "POST",
body: myArray,
});
request.arrayBuffer().then((buffer) => {
// do something with the buffer sent in the request
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Response.arrayBuffer()")}}
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/bodyused/index.md | ---
title: "Request: bodyUsed property"
short-title: bodyUsed
slug: Web/API/Request/bodyUsed
page-type: web-api-instance-property
browser-compat: api.Request.bodyUsed
---
{{APIRef("Fetch API")}}
The read-only **`bodyUsed`** property of the
{{domxref("Request")}} interface is a boolean value that indicates
whether the request body has been read yet.
## Value
A boolean value.
## Examples
```js
const request = new Request("/myEndpoint", {
method: "POST",
body: "Hello world",
});
request.bodyUsed; // false
request.text().then((bodyAsText) => {
console.log(request.bodyUsed); // true
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Request.body")}}
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/text/index.md | ---
title: "Request: text() method"
short-title: text()
slug: Web/API/Request/text
page-type: web-api-instance-method
browser-compat: api.Request.text
---
{{APIRef("Fetch API")}}
The **`text()`** method of the {{domxref("Request")}} interface
reads the request body and returns it as a promise that resolves with a {{jsxref("String")}}.
The response is _always_ decoded using UTF-8.
## Syntax
```js-nolint
text()
```
### Parameters
None.
### Return value
A Promise that resolves with a {{jsxref("String")}}.
## Examples
```js
const text = "Hello world";
const request = new Request("/myEndpoint", {
method: "POST",
body: text,
});
request.text().then((text) => {
// do something with the text sent in the request
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Response.text()")}}
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/headers/index.md | ---
title: "Request: headers property"
short-title: headers
slug: Web/API/Request/headers
page-type: web-api-instance-property
browser-compat: api.Request.headers
---
{{APIRef("Fetch API")}}
The **`headers`** read-only property of the
{{domxref("Request")}} interface contains the {{domxref("Headers")}} object associated
with the request.
## Value
A {{domxref("Headers")}} object.
## Examples
In the following snippet, we create a new request using the
{{domxref("Request.Request", "Request()")}} constructor (for an image file in the same directory as
the script), then save the request headers in a variable:
```js
const myRequest = new Request("flowers.jpg");
const myHeaders = myRequest.headers; // Headers {}
```
To add a header to the {{domxref("Headers")}} object we use
{{domxref("Headers.append")}}; we then create a new `Request` along with a
2nd init parameter, passing headers in as an init option:
```js
const myHeaders = new Headers();
myHeaders.append("Content-Type", "image/jpeg");
const myInit = {
method: "GET",
headers: myHeaders,
mode: "cors",
cache: "default",
};
const myRequest = new Request("flowers.jpg", myInit);
const myContentType = myRequest.headers.get("Content-Type"); // returns 'image/jpeg'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/url/index.md | ---
title: "Request: url property"
short-title: url
slug: Web/API/Request/url
page-type: web-api-instance-property
browser-compat: api.Request.url
---
{{APIRef("Fetch API")}}
The **`url`** read-only property of the {{domxref("Request")}}
interface contains the URL of the request.
## Value
A string indicating the URL of the request.
## Examples
In the following snippet, we create a new request using the
{{domxref("Request.Request", "Request()")}} constructor (for an image file in the same directory as
the script), then save the URL of the request in a variable:
```js
const myRequest = new Request("flowers.jpg");
const myURL = myRequest.url; // "https://github.com/mdn/dom-examples/tree/main/fetch/fetch-request/flowers.jpg"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/request/index.md | ---
title: "Request: Request() constructor"
short-title: Request()
slug: Web/API/Request/Request
page-type: web-api-constructor
browser-compat: api.Request.Request
---
{{APIRef("Fetch API")}}
The **`Request()`** constructor creates a new
{{domxref("Request")}} object.
## Syntax
```js-nolint
new Request(input)
new Request(input, options)
```
### Parameters
- `input`
- : Defines the resource that you wish to fetch. This can either be:
- A string containing the URL of the resource you want to fetch. The URL may be relative to the base URL, which is the document's {{domxref("Node.baseURI", "baseURI")}} in a window context, or {{domxref("WorkerGlobalScope.location")}} in a worker context.
- A {{domxref("Request")}} object, effectively creating a copy. Note the following
behavioral updates to retain security while making the constructor less likely to
throw exceptions:
- If this object exists on another origin to the constructor call, the
{{domxref("Request.referrer")}} is stripped out.
- If this object has a {{domxref("Request.mode")}} of `navigate`,
the `mode` value is converted to `same-origin`.
- `options` {{optional_inline}}
- : An object containing any custom settings that you want to apply to the
request. The possible options are:
- `method`
- : The request method, e.g., `GET`,
`POST`. The default is `GET`.
- `headers`
- : Any headers you want to add to your request, contained
within a {{domxref("Headers")}} object or an object literal with
{{jsxref("String")}} values.
- `body`
- : Any body that you want to add to your request: this can be a
{{domxref("Blob")}}, an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, a {{jsxref("DataView")}},
a {{domxref("FormData")}}, a {{domxref("URLSearchParams")}}, a string, or a {{domxref("ReadableStream")}} object.
Note that a request using the `GET` or `HEAD` method cannot have a body.
- `mode`
- : The mode you want to use for the request, e.g.,
`cors`, `no-cors`, `same-origin`, or
`navigate`. The default is `cors`.
- `credentials`
- : The request credentials you want to use for the
request: `omit`, `same-origin`, or `include`. The
default is `same-origin`.
- `cache`
- : The [cache mode](/en-US/docs/Web/API/Request/cache) you want to use for the request.
- `redirect`
- : The redirect mode to use: `follow`,
`error`, or `manual`. The default is `follow`.
- `referrer`
- : A string specifying
`no-referrer`, `client`, or a URL. The default is
`about:client`.
- `referrerPolicy`
- : A string that changes how the referrer header is populated during certain actions (e.g., fetching subresources, prefetching, performing navigations).
- `integrity`
- : Contains the [subresource integrity](/en-US/docs/Web/Security/Subresource_Integrity)
value of the request (e.g.,
`sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=`).
- `keepalive`
- : A boolean that indicates whether to make a persistent connection for multiple requests/responses.
- `signal`
- : An [AbortSignal](/en-US/docs/Web/API/AbortSignal) object which can be used to communicate with/abort a request.
- `priority`
- : Specifies the priority of the fetch request relative to other requests of the same type. Must be one of the following strings:
- `high`: A high priority fetch request relative to other requests of the same type.
- `low`: A low priority fetch request relative to other requests of the same type.
- `auto`: Automatically determine the priority of the fetch request relative to other requests of the same type (default).
If you construct a new `Request` from an existing `Request`, any options you set in an _options_ argument for the new request replace any corresponding options set in the original `Request`. For example:
```js
const oldRequest = new Request(
"https://github.com/mdn/content/issues/12959",
{ headers: { From: "[email protected]" } },
);
oldRequest.headers.get("From"); // "[email protected]"
const newRequest = new Request(oldRequest, {
headers: { From: "[email protected]" },
});
newRequest.headers.get("From"); // "[email protected]"
```
## Errors
<table class="no-markdown">
<thead>
<tr>
<th scope="col">Type</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>TypeError</code></td>
<td>
Since <a href="/en-US/docs/Mozilla/Firefox/Releases/43">Firefox 43</a>,
<code>Request()</code> will throw a TypeError if the URL has
credentials, such as http://user:[email protected].
</td>
</tr>
</tbody>
</table>
## Examples
In our [Fetch Request example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-request) (see [Fetch Request live](https://mdn.github.io/dom-examples/fetch/fetch-request/)) we
create a new `Request` object using the constructor, then fetch it using a
{{domxref("fetch()")}} call. Since we are fetching an image, we run
{{domxref("Response.blob")}} on the response to give it the proper MIME type so it will be
handled properly, then create an Object URL of it and display it in an
{{htmlelement("img")}} element.
```js
const myImage = document.querySelector("img");
const myRequest = new Request("flowers.jpg");
fetch(myRequest)
.then((response) => response.blob())
.then((response) => {
const objectURL = URL.createObjectURL(response);
myImage.src = objectURL;
});
```
In our [Fetch Request with init example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-with-init-then-request) (see [Fetch Request init live](https://mdn.github.io/dom-examples/fetch/fetch-with-init-then-request/)) we do the same thing except that we pass in an _options_ object when we
invoke `fetch()`:
```js
const myImage = document.querySelector("img");
const myHeaders = new Headers();
myHeaders.append("Content-Type", "image/jpeg");
const myOptions = {
method: "GET",
headers: myHeaders,
mode: "cors",
cache: "default",
};
const myRequest = new Request("flowers.jpg", myOptions);
fetch(myRequest).then((response) => {
// ...
});
```
Note that you could also pass `myOptions` into the `fetch` call to get
the same effect, e.g.:
```js
fetch(myRequest, myOptions).then((response) => {
// ...
});
```
You can also use an object literal as `headers` in `myOptions`.
```js
const myOptions = {
method: "GET",
headers: {
"Content-Type": "image/jpeg",
},
mode: "cors",
cache: "default",
};
const myRequest = new Request("flowers.jpg", myOptions);
```
You may also pass a {{domxref("Request")}} object to the `Request()`
constructor to create a copy of the Request (This is similar to calling the
{{domxref("Request.clone","clone()")}} method.)
```js
const copy = new Request(myRequest);
```
> **Note:** This last usage is probably only useful in [ServiceWorkers](/en-US/docs/Web/API/Service_Worker_API).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/integrity/index.md | ---
title: "Request: integrity property"
short-title: integrity
slug: Web/API/Request/integrity
page-type: web-api-instance-property
browser-compat: api.Request.integrity
---
{{APIRef("Fetch API")}}
The **`integrity`** read-only property of the {{domxref("Request")}} interface contains the [subresource integrity](/en-US/docs/Web/Security/Subresource_Integrity) value of the request.
## Value
The value that was passed as the `options.integrity` argument when constructing the `Request`.
If an integrity has not been specified, the property returns `''`.
## Examples
In the following snippet, we create a new request using the {{domxref("Request/Request", "Request()")}} constructor (for an image file in the same directory as the script), then reads the request's integrity. Because the request was created without a specific integrity, the property returns an empty string.
```js
const myRequest = new Request("flowers.jpg");
console.log(myRequest.integrity); // ""
```
In the example below, the request was created with a specific integrity value, so the property returns that value. Note that there's no validation of the integrity value; the property returns exactly what was passed in.
```js
const myRequest = new Request("flowers.jpg", {
integrity: "sha256-abc123",
});
console.log(myRequest.integrity); // "sha256-abc123"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/credentials/index.md | ---
title: "Request: credentials property"
short-title: credentials
slug: Web/API/Request/credentials
page-type: web-api-instance-property
browser-compat: api.Request.credentials
---
{{APIRef("Fetch API")}}
The **`credentials`** read-only property of the {{domxref("Request")}} interface indicates whether the user agent should send or receive cookies from the other domain in the case of cross-origin requests.
## Value
A `RequestCredentials` dictionary value indicating whether the user agent should send or receive cookies from the other domain in the case of cross-origin requests. Possible values are:
- `omit`
- : Never send or receive cookies.
- `same-origin`
- : Send user credentials (cookies, basic http auth, etc..) if the URL is on the same origin as the calling script. **This is the default value.**
- `include`
- : Always send user credentials (cookies, basic http auth, etc..), even for cross-origin calls.
This is similar to XHR's [`withCredentials`](/en-US/docs/Web/API/XMLHttpRequest/withCredentials) flag, but with three available values instead of two.
## Examples
In the following snippet, we create a new request using the {{domxref("Request.Request", "Request()")}} constructor (for an image file in the same directory as the script), then save the request credentials in a variable:
```js
const myRequest = new Request("flowers.jpg");
const myCred = myRequest.credentials; // returns "same-origin" by default
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/referrerpolicy/index.md | ---
title: "Request: referrerPolicy property"
short-title: referrerPolicy
slug: Web/API/Request/referrerPolicy
page-type: web-api-instance-property
browser-compat: api.Request.referrerPolicy
---
{{APIRef("Fetch API")}}
The **`referrerPolicy`** read-only property of the
{{domxref("Request")}} interface returns the referrer policy, which governs what
referrer information, sent in the {{HTTPHeader("Referer")}} header, should be included
with the request.
## Value
A string representing the request's `referrerPolicy`. For
more information and possible values, see the {{HTTPHeader("Referrer-Policy")}} HTTP
header page.
## Examples
In the following snippet, we create a new request using the
{{domxref("Request.Request", "Request()")}} constructor (for an image file in the same directory as
the script), then save the request referrer policy in a variable:
```js
const myRequest = new Request("flowers.jpg");
const myReferrer = myRequest.referrerPolicy; // returns "" by default
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
- [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS)
- [HTTP](/en-US/docs/Web/HTTP)
| 0 |
data/mdn-content/files/en-us/web/api/request | data/mdn-content/files/en-us/web/api/request/formdata/index.md | ---
title: "Request: formData() method"
short-title: formData()
slug: Web/API/Request/formData
page-type: web-api-instance-method
browser-compat: api.Request.formData
---
{{APIRef("Fetch API")}}
The **`formData()`** method of the {{domxref("Request")}} interface
reads the request body and returns it as a promise that resolves with a {{domxref("FormData")}} object.
## Syntax
```js-nolint
formData()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves with a {{domxref("FormData")}} object.
## Examples
```js
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append("username", "abc123");
formData.append("avatar", fileField.files[0]);
const request = new Request("/myEndpoint", {
method: "POST",
body: formData,
});
request.formData().then((data) => {
// do something with the formdata sent in the request
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Response.formData()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/videoplaybackquality/index.md | ---
title: VideoPlaybackQuality
slug: Web/API/VideoPlaybackQuality
page-type: web-api-interface
browser-compat: api.VideoPlaybackQuality
---
{{APIRef("HTML DOM")}}
A **`VideoPlaybackQuality`** object is returned by the {{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} method and contains metrics that can be used to determine the playback quality of a video.
## Instance properties
_The `VideoPlaybackQuality` interface doesn't inherit properties from any other interfaces._
- {{domxref("VideoPlaybackQuality.creationTime", "creationTime")}} {{ReadOnlyInline}}
- : A {{domxref("DOMHighResTimeStamp")}} containing the time in milliseconds between the start of the navigation and the creation of the object.
- {{domxref("VideoPlaybackQuality.droppedVideoFrames", "droppedVideoFrames")}} {{ReadOnlyInline}}
- : An `unsigned long` giving the number of video frames dropped since the creation of the associated {{domxref("HTMLVideoElement")}}.
- {{domxref("VideoPlaybackQuality.totalVideoFrames", "totalVideoFrames")}} {{ReadOnlyInline}}
- : An `unsigned long` giving the number of video frames created and dropped since the creation of the associated {{domxref("HTMLVideoElement")}}.
### Obsolete properties
- {{domxref("VideoPlaybackQuality.corruptedVideoFrames", "corruptedVideoFrames")}} {{ReadOnlyInline}} {{Deprecated_Inline}}
- : An `unsigned long` giving the number of video frames corrupted since the creation of the associated {{domxref("HTMLVideoElement")}}. A corrupted frame may be created or dropped.
- {{domxref("VideoPlaybackQuality.totalFrameDelay", "totalFrameDelay")}} {{ReadOnlyInline}} {{deprecated_inline}} {{Non-standard_Inline}}
- : A `double` containing the sum of the frame delay since the creation of the associated {{domxref("HTMLVideoElement")}}. The frame delay is the difference between a frame's theoretical presentation time and its effective display time.
## Instance methods
_The `VideoPlaybackQuality` interface has no methods, and does not inherit any._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} method to get a `VideoPlaybackQuality` object
- {{domxref("MediaSource")}}
- {{domxref("SourceBuffer")}}
| 0 |
data/mdn-content/files/en-us/web/api/videoplaybackquality | data/mdn-content/files/en-us/web/api/videoplaybackquality/totalframedelay/index.md | ---
title: "VideoPlaybackQuality: totalFrameDelay property"
short-title: totalFrameDelay
slug: Web/API/VideoPlaybackQuality/totalFrameDelay
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VideoPlaybackQuality.totalFrameDelay
---
{{APIRef("Media Source Extensions")}}{{deprecated_header}}{{Non-standard_header}}
The **`VideoPlaybackQuality.totalFrameDelay`** read-only
property returns a `double` containing the sum of the frame delay since the
creation of the associated {{domxref("HTMLVideoElement")}}. The frame delay is the
difference between a frame's theoretical presentation time and its effective display
time.
## Value
A number.
## Examples
```js
const videoElt = document.getElementById("my_vid");
const quality = videoElt.getVideoPlaybackQuality();
alert(quality.totalFrameDelay);
```
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} method for
constructing and returning this interface.
- {{domxref("MediaSource")}}
- {{domxref("SourceBuffer")}}
| 0 |
data/mdn-content/files/en-us/web/api/videoplaybackquality | data/mdn-content/files/en-us/web/api/videoplaybackquality/totalvideoframes/index.md | ---
title: "VideoPlaybackQuality: totalVideoFrames property"
short-title: totalVideoFrames
slug: Web/API/VideoPlaybackQuality/totalVideoFrames
page-type: web-api-instance-property
browser-compat: api.VideoPlaybackQuality.totalVideoFrames
---
{{APIRef("HTML DOM")}}
The {{domxref("VideoPlaybackQuality")}} interface's
**`totalVideoFrames`** read-only property returns the total
number of video frames that have been displayed or dropped since the media was
loaded.
## Value
The total number of frames that the {{HTMLElement("video")}} element has displayed or
dropped since the media was loaded into it. Essentially, this is the number of frames
the element _would have presented_ had no problems occurred.
This value is reset when the media is reloaded or replaced.
## Examples
This example calls {{domxref("HTMLVideoElement.getVideoPlaybackQuality",
"getVideoPlaybackQuality()")}} to obtain a {{domxref("VideoPlaybackQuality")}} object,
then determines what percentage of frames have been lost by either corruption or being
dropped. If that exceeds 10% (0.1), a function called
`lostFramesThresholdExceeded()` is called to, perhaps, update a quality
indicator to show an increase in frame loss.
```js
const videoElem = document.getElementById("my_vid");
const quality = videoElem.getVideoPlaybackQuality();
if (
(quality.corruptedVideoFrames + quality.droppedVideoFrames) /
quality.totalVideoFrames >
0.1
) {
lostFramesThresholdExceeded();
}
```
A similar algorithm might be used to attempt to switch to a lower-resolution video that
requires less bandwidth, in order to avoid dropping frames.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} method for
constructing and returning this interface.
| 0 |
data/mdn-content/files/en-us/web/api/videoplaybackquality | data/mdn-content/files/en-us/web/api/videoplaybackquality/corruptedvideoframes/index.md | ---
title: "VideoPlaybackQuality: corruptedVideoFrames property"
short-title: corruptedVideoFrames
slug: Web/API/VideoPlaybackQuality/corruptedVideoFrames
page-type: web-api-instance-property
status:
- deprecated
browser-compat: api.VideoPlaybackQuality.corruptedVideoFrames
---
{{APIRef("HTML DOM")}}{{deprecated_header}}
The {{domxref("VideoPlaybackQuality")}} interface's read-only
**`corruptedVideoFrames`** property the number of corrupted
video frames that have been received since the {{HTMLElement("video")}} element was
last loaded or reloaded.
## Value
The number of corrupted video frames that have been received since the
{{HTMLElement("video")}} element was last loaded or reloaded.
It is up to the {{Glossary("user agent")}} to determine whether or not to display a
corrupted video frame. If a corrupted frame is dropped, then both
`corruptedVideoFrames` and
{{domxref("VideoPlaybackQuality.droppedVideoFrames", "droppedVideoFrames")}} are
incremented.
## Examples
This example determines the percentage of frames which have been corrupted, and if the
value is greater than 5%, calls a function called `downgradeVideo()` that
would be implemented to switch to a different video that might tax the network less.
```js
const videoElem = document.getElementById("my_vid");
const quality = videoElem.getVideoPlaybackQuality();
if (quality.corruptedVideoFrames / quality.totalVideoFrames > 0.05) {
downgradeVideo(videoElem);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} method for
constructing and returning this interface
| 0 |
data/mdn-content/files/en-us/web/api/videoplaybackquality | data/mdn-content/files/en-us/web/api/videoplaybackquality/creationtime/index.md | ---
title: "VideoPlaybackQuality: creationTime property"
short-title: creationTime
slug: Web/API/VideoPlaybackQuality/creationTime
page-type: web-api-instance-property
browser-compat: api.VideoPlaybackQuality.creationTime
---
{{APIRef("HTML DOM")}}
The read-only **`creationTime`** property on the
{{domxref("VideoPlaybackQuality")}} interface reports the number of milliseconds since
the browsing context was created this quality sample was recorded.
## Value
A {{domxref("DOMHighResTimeStamp")}} object which indicates the number of milliseconds
that elapsed between the time the browsing context was created and the time at which
this sample of the video quality was obtained.
For details on how the time is determined, see {{domxref("Performance.now()")}}.
## Examples
This example calls `getVideoPlaybackQuality()` to obtain a
{{domxref("VideoPlaybackQuality")}} object, then determines what percentage of frames
have been lost by either corruption or being dropped. If that exceeds 10% (0.1), a
function called `lostFramesThresholdExceeded()` is called to, perhaps,
update a quality indicator to show an increase in frame loss.
```js
const videoElem = document.getElementById("my_vid");
const quality = videoElem.getVideoPlaybackQuality();
if (
(quality.corruptedVideoFrames + quality.droppedVideoFrames) /
quality.totalVideoFrames >
0.1
) {
lostFramesThresholdExceeded();
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} method, which
returns `VideoPlaybackQuality` objects
| 0 |
data/mdn-content/files/en-us/web/api/videoplaybackquality | data/mdn-content/files/en-us/web/api/videoplaybackquality/droppedvideoframes/index.md | ---
title: "VideoPlaybackQuality: droppedVideoFrames property"
short-title: droppedVideoFrames
slug: Web/API/VideoPlaybackQuality/droppedVideoFrames
page-type: web-api-instance-property
browser-compat: api.VideoPlaybackQuality.droppedVideoFrames
---
{{APIRef("HTML DOM")}}
The read-only **`droppedVideoFrames`**
property of the {{domxref("VideoPlaybackQuality")}} interface returns the number of
video frames which have been dropped rather than being displayed since the last time
the media was loaded into the {{domxref("HTMLVideoElement")}}.
## Value
An unsigned 64-bit value indicating the number of frames that have been dropped since
the last time the media in the {{HTMLElement("video")}} element was loaded or reloaded.
This information can be used to determine whether or not to downgrade the video stream
to avoid dropping frames.
Frames are typically dropped either before or after decoding them, when it's determined
that it will not be possible to draw them to the screen at the correct time.
## Examples
This example calls {{domxref("HTMLVideoElement.getVideoPlaybackQuality",
"getVideoPlaybackQuality()")}} to obtain a {{domxref("VideoPlaybackQuality")}} object,
then determines what percentage of frames have been dropped. That value is then
presented in an element for the user's reference.
```js
const videoElem = document.getElementById("my_vid");
const percentElem = document.getElementById("percent");
const quality = videoElem.getVideoPlaybackQuality();
const dropPercent =
(quality.droppedVideoFrames / quality.totalVideoFrames) * 100;
percentElem.innerText = Math.trunc(dropPercent).toString(10);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} method, which creates
and returns `VideoPlaybackQuality` objects
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/web_crypto_api/index.md | ---
title: Web Crypto API
slug: Web/API/Web_Crypto_API
page-type: web-api-overview
browser-compat: api.Crypto
---
{{DefaultAPISidebar("Web Crypto API")}}
The **Web Crypto API** is an interface allowing a script to use cryptographic primitives in order to build systems using cryptography.
{{AvailableInWorkers}}
{{securecontext_header}}
> **Warning:** The Web Crypto API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle.
>
> Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts.
>
> Errors in security system design and implementation can make the security of the system completely ineffective.
>
> Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems.
## Interfaces
Some browsers implemented an interface called {{domxref("Crypto")}} without having it well defined or being cryptographically sound. In order to avoid confusion, methods and properties of this interface have been removed from browsers implementing the Web Crypto API, and all Web Crypto API methods are available on a new interface: {{domxref("SubtleCrypto")}}. The {{domxref("Crypto.subtle")}} property gives access to an object implementing it.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/web_crypto_api | data/mdn-content/files/en-us/web/api/web_crypto_api/non-cryptographic_uses_of_subtle_crypto/index.md | ---
title: Non-cryptographic uses of SubtleCrypto
slug: Web/API/Web_Crypto_API/Non-cryptographic_uses_of_subtle_crypto
page-type: guide
---
{{DefaultAPISidebar("Web Crypto API")}}
This article will focus on uses of the [`digest`](/en-US/docs/Web/API/SubtleCrypto/digest) method of the [SubtleCrypto interface](/en-US/docs/Web/API/SubtleCrypto). A lot of other methods within the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) have very specific cryptographic use cases, creating hashes of content (which is what the digest method does) has lots of very useful purposes.
This article does not discuss the cryptographic uses of the [SubtleCrypto interface](/en-US/docs/Web/API/SubtleCrypto). An important thing to take away from this article is **don't use this API** for production cryptographic purposes because it is powerful and low level. To use it correctly you will need to take many context specific steps to accomplish cryptographic tasks correctly. If any of those steps are taken incorrectly at best your code won't run, at worse it _will_ run and you will unknowingly be putting your users at risk with an insecure product.
You may not even need to use the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) at all. Many of the things you would want to use cryptography for are already solved and part of the Web platform. For example, if you are worried about man-in-the-middle attacks, such as Wi-Fi hotspots reading the information between the client and the server, this is solved by ensuring correct use of [HTTPS](/en-US/docs/Glossary/HTTPS). Do you want to securely send information between users? Then you can set up a data connection between users using [WebRTC Data Channels](/en-US/docs/Web/API/WebRTC_API/Using_data_channels) which is encrypted as part of the standard.
The [SubtleCrypto interface](/en-US/docs/Web/API/SubtleCrypto) provides low level primitives for working with cryptography, but implementing a system using these tools is a complicated task. Mistakes are hard to notice and the results can mean your user's data is not as secure as you think it is. Which could have catastrophic results if your users are sharing sensitive or valuable data.
If in doubt don't try doing it yourself, hire someone with experience and ensure your software is audited by a security expert.
## Hashing a file
This is the simplest useful thing you can do with the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API). It doesn't involve generating keys or certificates and has one single step.
[Hashing](/en-US/docs/Glossary/Hash) is a technique where you convert a large string of bytes into a smaller string, where small changes to the long string result in large changes in the smaller string. This technique is useful for identifying two identical files without checking every byte of both files. This is very useful as you have a simple string to compare. To be clear hashing is a **one way** operation. You cannot generate the original string of bytes from the hash.
If two generated hashes are the same, but the files that used to generate them are different, that is known as a _hash collision_ which is an extremely improbable thing to occur by accident and, for a secure hash function like SHA256, almost impossible to manufacture. So if the two strings are the same you can be reasonably sure the two original files are identical.
As of publication, SHA256 is the usual choice for hashing files but there are [higher order hashing functions](/en-US/docs/Web/API/SubtleCrypto#supported_algorithms) available in the SubtleCrypto interface. The most common representation of a SHA256 hash is a string of 64 hexadecimal digits. Hexadecimal means it only uses the characters 0-9 and a-f, representing 4 bits of information. So in short a SHA256 hash turns any length of data into an almost unique 256 bits of data.
This technique is often used by sites that let you download executables, to ensure that the downloaded file matches the one the author intended. This ensures that your users are not installing malware. The most common way to do this is:
1. Note down the file's name and the SHA256 checksum provided by the website.
2. Download the executable.
3. Run `sha256sum /path/to/the/file` in the terminal to generate your own code. If you are using a Mac you may have to [install it separately](https://unix.stackexchange.com/questions/426837/no-sha256sum-in-macos).
4. Compare the two strings - they should match unless the file has been compromised.

The [`digest()`](/en-US/docs/Web/API/SubtleCrypto/digest) method of SubtleCrypto is useful for this. To generate a checksum of a file you can do it like so:
First we add some HTML elements for loading some files and displaying the SHA-256 output:
```html
<h3>Demonstration of hashing a file with SHA256</h3>
<label
>Choose file(s) to hash <input type="file" id="file" name="file" multiple
/></label>
<output style="display:block;font-family:monospace;"></output>
```
Next we use the SubtleCrypto interface to process them. This works by:
- Reading the files to an {{jsxref("ArrayBuffer")}} using the {{domxref("File")}} object's {{domxref("Blob.arrayBuffer()", "arrayBuffer()")}} method.
- Use `crypto.subtle.digest('SHA-256', arrayBuffer)` to digest the ArrayBuffer
- Convert the resulting hash (another ArrayBuffer) into a string so it can be displayed
```js
const output = document.querySelector("output");
const file = document.getElementById("file");
// Run the hashing function when the user selects one or more file
file.addEventListener("change", hashTheseFiles);
// The digest function is asynchronous, it returns a promise
// We use the async/await syntax to simplify the code.
async function fileHash(file) {
const arrayBuffer = await file.arrayBuffer();
// Use the subtle crypto API to perform a SHA256 Sum of the file's
// Array Buffer. The resulting hash is stored in an array buffer
const hashAsArrayBuffer = await crypto.subtle.digest("SHA-256", arrayBuffer);
// To display it as a string we will get the hexadecimal value of
// each byte of the array buffer. This gets us an array where each byte
// of the array buffer becomes one item in the array
const uint8ViewOfHash = new Uint8Array(hashAsArrayBuffer);
// We then convert it to a regular array so we can convert each item
// to hexadecimal strings, where characters of 0-9 or a-f represent
// a number between 0 and 15, containing 4 bits of information,
// so 2 of them is 8 bits (1 byte).
const hashAsString = Array.from(uint8ViewOfHash)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return hashAsString;
}
async function hashTheseFiles(e) {
let outHTML = "";
// iterate over each file in file select input
for (const file of this.files) {
// calculate its hash and list it in the output element.
outHTML += `${file.name} ${await fileHash(file)}`;
}
output.innerHTML = outHTML;
}
```
{{EmbedLiveSample("hashing_a_file")}}
### Where would you use this?
At this point you may be thinking to yourself "_I can use this on my own website, so when users go to download a file we can ensure the hashes match to reassure the user their download is secure_". Unfortunately this has two issues that immediate spring to mind:
- Executable downloads should **always** be done over HTTPS. This prevents intermediate parties from performing attacks like this so it would be redundant.
- If the attacker is able to replace the download file on the original server, then they can also simply replace the code which invokes the SubtleCrypto interface to bypass it and just state that everything is fine. Probably something sneaky like replacing [strict equality](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#strict_equality_using), which can be a pain to spot in your own code:
```diff
--- if (checksum === correctCheckSum) return true;
+++ if (checksum = correctCheckSum) return true;
```
One place it may be worthwhile, is if you want to test a file from a third party download source, which you do not control. This would be the case as long as the download location has [CORS](/en-US/docs/Glossary/CORS) headers enabled to let you scan the file before you make it available to your users. Unfortunately not many servers have CORS turned on by default.
## What is "Salting the Hash"?
A phrase you may have heard before is _"Salting the hash"_. It's not immediately relevant to our topics at hand, but it is good to know about.
> **Note:** this section is talking about password security and the hash functions provided by SubtleCrypto are not suitable for this use case. For these purposes you need expensive slow hash functions like `scrypt` and `bcrypt`. SHA is designed to be pretty fast and efficient, which makes it unsuitable for password hashing. This section is purely for your interest — do not use the Web Crypto API to hash passwords on the client.
A popular use case for hashing is passwords, you never ever want to store a users password in plain text, its simply a terrible idea. Instead you store a hash of the users password, so the original password cannot be recovered should a hacker obtain your username and password database. The eagle eyed among may notice you can still work out the original passwords by comparing the hashes from lists of known passwords against the obtained password hash list. Concatenating a string to the passwords changes the hash so it no longer matches. This is known as **salting**. Another tricky problem is if you use the same salt for each password, then passwords with matching hashes will also be the same original password. Thus if you know one then you know all matching passwords.
To solve this issue, you perform what is known as _salting the hash_. For each password, you generate a salt (a random string of characters) and concatenate that with the password string. You then store the hash and the salt in the same database so you can check a match when the user tries to log in later. This means that if two users use the same password the hashes will be different. Hence the reason why you need an expensive cryptographic function, so it makes it too time consuming to use lists of common passwords to find out what the original passwords were.
## Hash Tables with SHA
You can use SHA1 to quickly generate non-cryptographically secure hashes. These are incredibly useful for turning some arbitrary data into a key you can look up later.
For example, if you want to have a database which includes a large blob of data as one of the fields in a row. This decreases the efficiency of your database because one of the fields has to be either variable length, or large enough to store the largest possible blob. An alternative solution is to generate a hash of the blob and store it in a separate look up table using the hash as the index. You can then store just the hash in your original database which is a nice fixed length.
The possible variations for a SHA1 hash are incredibly numerous. So much so that accidentally producing two blobs with the same SHA1 hash is nearly-impossible. It _is_ possible to intentionally produce two files with the same SHA1 hash, because SHA1 is not cryptographically secure. So a malicious user could in theory generate a blob of data that replaces the original in the database, which goes undetected because the hash is the same. This is an attack vector worth being aware of.
## How git stores files
Git uses SHA1 hashes and is a great example here, it uses hashes in two interesting ways. When files are stored in git, they are referenced by their SHA1 hash. This makes it quick for git to find the data and restore files.
It doesn't just use the file contents for the hash however, it also prepends it with the UTF8 string `"blob "`, followed by the file size in bytes written in decimal, followed by the null character (which in JavaScript can be written `"\0"`). You can use the [TextEncoder interface](/en-US/docs/Web/API/TextEncoder) of the [Encoding API](/en-US/docs/Web/API/Encoding_API) to encode the UTF8 text, since strings in JavaScript are UTF16.
The code below, like our SHA256 example, can be used to generate these hashes from files. The HTML to upload files remains the same, but we do some additional work to prepend the size information in the same way git does.
```html
<h3>Demonstration of how git uses SHA1 for files</h3>
<label
>Choose file(s) to hash <input type="file" id="file" name="file" multiple
/></label>
<output style="display:block;font-family:monospace;"></output>
```
```js
const output = document.querySelector("output");
const file = document.getElementById("file");
file.addEventListener("change", hashTheseFiles);
async function fileHash(file) {
const arrayBuffer = await file.arrayBuffer();
// Git prepends the null terminated text 'blob 1234' where 1234
// represents the file size before hashing so we are going to reproduce that
// first we work out the Byte length of the file
const uint8View = new Uint8Array(arrayBuffer);
const length = uint8View.length;
// Git in the terminal uses UTF8 for its strings; the Web uses UTF16.
// We need to use an encoder because different binary representations
// of the letters in our message will result in different hashes
const encoder = new TextEncoder();
// Null-terminated means the string ends in the null character which
// in JavaScript is '\0'
const view = encoder.encode(`blob ${length}\0`);
// We then combine the 2 Array Buffers together into a new Array Buffer.
const newBlob = new Blob([view.buffer, arrayBuffer], {
type: "text/plain",
});
const arrayBufferToHash = await newBlob.arrayBuffer();
// Finally we perform the hash this time as SHA1 which is what Git uses.
// Then we return it as a string to be displayed.
return hashToString(await crypto.subtle.digest("SHA-1", arrayBufferToHash));
}
function hashToString(arrayBuffer) {
const uint8View = new Uint8Array(arrayBuffer);
return Array.from(uint8View)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
// like before we iterate over the files
async function hashTheseFiles(e) {
let outHTML = "";
for (const file of this.files) {
outHTML += `${file.name} ${await fileHash(file)}`;
}
output.innerHTML = outHTML;
}
```
{{EmbedLiveSample("how-git-stores-files")}}
Notice how it uses the [Encoding API](/en-US/docs/Web/API/Encoding_API) to produce the header, which is concatenated with the original ArrayBuffer to produce the string to be hashed.
## How git generates commit hashes
Interestingly git also generates commit hashes in a similar way based upon multiple pieces of information. These can include the previous commit hash and the commit message, which come together to make a new hash. This can be used to reference commits which are based on several unique identifiers.
The terminal command is: `(printf "commit %s\0" $(git --no-replace-objects cat-file commit HEAD | wc -c); git cat-file commit HEAD) | sha1sum`
Source: [How is git commit sha1 formed](https://gist.github.com/masak/2415865)
Essentially it's the UTF8 string (null character written as `\0`):
```plain
commit [size in bytes as decimal of this info]\0tree [tree hash]
parent [parent commit hash]
author [author info] [timestamp]
committer [committer info] [timestamp]
commit message
```
This is great because none of the individual fields are guaranteed to be unique, but when combined together give a unique pointer to a single commit. However, the whole string is too long and unwieldy to use. So by hashing it you get a new unique string which is short enough to share conveniently from multiple fields.
This is why the hash changes if you have ever amended your commit, even if you don't make any changes to the message. The timestamp of the commit has changed, which even by a single character, is enough to totally change the new hash.
The take away from this is that when you want to add a key to some data, but any single piece of information isn't unique enough, then concatenating multiple strings together and hashing them is a great way to generate a useful key.
Hopefully these examples have encourage you to take a look at this new powerful API. Remember don't try recreating cryptography things yourself. Its enough to know the tools are there and some of them like the [`crypto.digest()`](/en-US/docs/Web/API/SubtleCrypto/digest) function are useful tools for your day to day development.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssstylerule/index.md | ---
title: CSSStyleRule
slug: Web/API/CSSStyleRule
page-type: web-api-interface
browser-compat: api.CSSStyleRule
---
{{ APIRef("CSSOM") }}
The **`CSSStyleRule`** interface represents a single CSS style rule.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its ancestor {{domxref("CSSRule")}}._
- {{domxref("CSSStyleRule.selectorText")}}
- : Returns the textual representation of the selector for this rule, e.g. `"h1, h2"`.
- {{domxref("CSSStyleRule.style")}} {{ReadOnlyInline}}
- : Returns the {{domxref("CSSStyleDeclaration")}} object for the rule.
- {{domxref("CSSStyleRule.styleMap")}} {{ReadOnlyInline}}
- : Returns a {{domxref('StylePropertyMap')}} object which provides access to the rule's property-value pairs.
## Instance methods
_No specific methods; inherits methods from its ancestor {{domxref("CSSRule")}}._
## Examples
The CSS includes one style rule. This will be the first {{domxref("CSSRule")}} returned by `document.styleSheets[0].cssRules`.
`myRules[0]` therefore returns a {{domxref("CSSStyleRule")}} object representing the rule defined for `h1`.
```css
h1 {
color: pink;
}
```
```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); // a CSSStyleRule representing the h1.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstylerule | data/mdn-content/files/en-us/web/api/cssstylerule/style/index.md | ---
title: "CSSStyleRule: style property"
short-title: style
slug: Web/API/CSSStyleRule/style
page-type: web-api-instance-property
browser-compat: api.CSSStyleRule.style
---
{{ APIRef("CSSOM") }}
The read-only **`style`** property is the {{ domxref("CSSStyleDeclaration") }} interface for the [declaration block](https://www.w3.org/TR/1998/REC-CSS2-19980512/syndata.html#block) of the {{ DOMXref("CSSStyleRule") }}.
## Value
A {{domxref("CSSStyleDeclaration")}} object, with the following properties:
- computed flag
- : Unset.
- declarations
- : The declared declarations in the rule, in the order they were specified, shorthand properties expanded to longhands.
- parent CSS rule
- : The context object, which is an alias for [this](https://heycam.github.io/webidl/#this).
- owner node
- : Null.
## Examples
The CSS includes one style rule. This will be the first {{domxref("CSSRule")}} returned by `document.styleSheets[0].cssRules`.
`myRules[0].style` therefore returns a {{domxref("CSSStyleDeclaration")}} object representing the declarations defined for `h1`.
```css
h1 {
color: pink;
}
```
```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0].style); // a CSSStyleDeclaration representing the declarations on the h1.
```
> **Note:** The declaration block is that part of the style rule that appears within the braces and that actually provides the style definitions (for the selector, the part that comes before the braces).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstylerule | data/mdn-content/files/en-us/web/api/cssstylerule/stylemap/index.md | ---
title: "CSSStyleRule: styleMap property"
short-title: styleMap
slug: Web/API/CSSStyleRule/styleMap
page-type: web-api-instance-property
browser-compat: api.CSSStyleRule.styleMap
---
{{APIRef("CSSOM")}}
The **`styleMap`** read-only property of the
{{domxref("CSSStyleRule")}} interface returns a {{domxref('StylePropertyMap')}} object
which provides access to the rule's property-value pairs.
## Value
A {{domxref('StylePropertyMap')}} object.
## Example
The following example shows `styleMap` being used to modify a style using
the {{domxref('StylePropertyMap.set()')}} method.
```js
const stylesheet = document.styleSheets[0];
Object.values(stylesheet.cssRules).forEach((block) => {
if (block.selectorText === "button") {
block.styleMap.set("--mainColor", "black");
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstylerule | data/mdn-content/files/en-us/web/api/cssstylerule/selectortext/index.md | ---
title: "CSSStyleRule: selectorText property"
short-title: selectorText
slug: Web/API/CSSStyleRule/selectorText
page-type: web-api-instance-property
browser-compat: api.CSSStyleRule.selectorText
---
{{APIRef("CSSOM") }}
The **`selectorText`** property of the {{domxref("CSSStyleRule")}} interface gets and sets the selectors associated with the `CSSStyleRule`.
## Value
A string.
## Examples
The CSS includes one style rule. This will be the first {{domxref("CSSRule")}} returned by `document.styleSheets[0].cssRules`. `myRules[0].selectorText` therefore returns a literal string of the selector, in this case `"h1"`.
```css
h1 {
color: pink;
}
```
```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0].selectorText); // a string containing "h1".
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/performancemark/index.md | ---
title: PerformanceMark
slug: Web/API/PerformanceMark
page-type: web-api-interface
browser-compat: api.PerformanceMark
---
{{APIRef("Performance API")}}
**`PerformanceMark`** is an interface for {{domxref("PerformanceEntry")}} objects with an {{domxref("PerformanceEntry.entryType","entryType")}} of "`mark`".
Entries of this type are typically created by calling {{domxref("Performance.mark","performance.mark()")}} to add a _named_ {{domxref("DOMHighResTimeStamp")}} (the _mark_) to the browser's performance timeline. To create a performance mark that isn't added to the browser's performance timeline, use the constructor.
{{InheritanceDiagram}}
{{AvailableInWorkers}}
## Constructor
- {{domxref("PerformanceMark.PerformanceMark", "PerformanceMark()")}}
- : Creates a new `PerformanceMark` object that isn't added to the browser's performance timeline.
## Instance properties
This interface extends the following {{domxref("PerformanceEntry")}} properties by qualifying/constraining the properties as follows:
- {{domxref("PerformanceEntry.entryType")}} {{ReadOnlyInline}}
- : Returns "`mark`".
- {{domxref("PerformanceEntry.name")}} {{ReadOnlyInline}}
- : Returns the name given to the mark when it was created via a call to {{domxref("Performance.mark()","performance.mark()")}}.
- {{domxref("PerformanceEntry.startTime")}} {{ReadOnlyInline}}
- : Returns the {{domxref("DOMHighResTimeStamp")}} when {{domxref("Performance.mark()","performance.mark()")}} was called.
- {{domxref("PerformanceEntry.duration")}} {{ReadOnlyInline}}
- : Returns "`0`". (A mark has no _duration_.)
This interface also supports the following properties:
- {{domxref("PerformanceMark.detail")}} {{ReadOnlyInline}}
- : Returns arbitrary metadata that has been included in the mark upon construction.
## Instance methods
This interface has no methods.
## Example
See the example in [Using the User Timing API](/en-US/docs/Web/API/Performance_API/User_timing).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [User Timing (Overview)](/en-US/docs/Web/API/Performance_API/User_timing)
- [Using the User Timing API](/en-US/docs/Web/API/Performance_API/User_timing)
| 0 |
data/mdn-content/files/en-us/web/api/performancemark | data/mdn-content/files/en-us/web/api/performancemark/detail/index.md | ---
title: "PerformanceMark: detail property"
short-title: detail
slug: Web/API/PerformanceMark/detail
page-type: web-api-instance-property
browser-compat: api.PerformanceMark.detail
---
{{APIRef("Performance API")}}
The read-only **`detail`** property returns arbitrary metadata that was included in the mark upon construction (either when using {{domxref("Performance.mark","performance.mark()")}} or the {{domxref("PerformanceMark.PerformanceMark","PerformanceMark()")}} constructor).
## Value
Returns the value it is set to (from `markOptions` of {{domxref("Performance.mark","performance.mark()")}} or the {{domxref("PerformanceMark.PerformanceMark","PerformanceMark()")}} constructor).
## Examples
The following example demonstrates the `detail` property.
```js
performance.mark("dog", { detail: "labrador" });
const dogEntries = performance.getEntriesByName("dog");
dogEntries[0].detail; // labrador
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/performancemark | data/mdn-content/files/en-us/web/api/performancemark/performancemark/index.md | ---
title: "PerformanceMark: PerformanceMark() constructor"
short-title: PerformanceMark()
slug: Web/API/PerformanceMark/PerformanceMark
page-type: web-api-constructor
browser-compat: api.PerformanceMark.PerformanceMark
---
{{APIRef("Performance API")}}
The **`PerformanceMark()`** constructor creates a {{domxref("DOMHighResTimeStamp","timestamp")}} with the given name.
Unlike {{domxref("Performance.mark","performance.mark()")}}, performance marks created by the constructor aren't added to the browser's performance timeline. This means that calls to the {{domxref("Performance")}} interface's `getEntries*()` methods ({{domxref("Performance.getEntries","getEntries()")}}, {{domxref("Performance.getEntriesByName","getEntriesByName()")}} or {{domxref("Performance.getEntriesByType","getEntriesByType()")}}) won't show entries for these marks.
## Syntax
```js-nolint
new PerformanceMark(name)
new PerformanceMark(name, markOptions)
```
### Parameters
- `name`
- : A string representing the name of the mark.
- `markOptions` {{optional_inline}}
- : An object for specifying a timestamp and additional metadata for the mark.
- `detail` {{optional_inline}}
- : Arbitrary metadata to include in the mark. Defaults to `null`.
- `startTime` {{optional_inline}}
- : {{domxref("DOMHighResTimeStamp")}} to use as the mark time. Defaults to {{domxref("performance.now()")}}.
### Return value
A {{domxref("PerformanceMark")}} object.
### Exceptions
- {{jsxref("SyntaxError")}}: Thrown if the `name` given to this method already exists in the {{domxref("PerformanceTiming")}} interface.
- {{jsxref("TypeError")}}: Thrown if `startTime` is negative.
## Examples
The following example shows how {{domxref("PerformanceMark")}} entries are constructed and then aren't part of the browser's performance timeline.
```js
new PerformanceMark("squirrel");
new PerformanceMark("monkey");
new PerformanceMark("dog");
const allEntries = performance.getEntriesByType("mark");
console.log(allEntries.length);
// 0
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Performance.mark","performance.mark()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssunparsedvalue/index.md | ---
title: CSSUnparsedValue
slug: Web/API/CSSUnparsedValue
page-type: web-api-interface
browser-compat: api.CSSUnparsedValue
---
{{APIRef("CSS Typed OM")}}
The **`CSSUnparsedValue`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents property values that reference [custom properties](/en-US/docs/Web/CSS/CSS_cascading_variables). It consists of a list of string fragments and variable references.
Custom properties are represented by `CSSUnparsedValue` and {{cssxref("var", "var()")}} references are represented using {{domxref('CSSVariableReferenceValue')}}.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CSSUnparsedValue.CSSUnparsedValue", "CSSUnparsedValue()")}}
- : Creates a new `CSSUnparsedValue` object.
## Instance properties
- {{domxref('CSSUnparsedValue.length')}}
- : Returns the number of items in the `CSSUnparsedValue` object.
## Instance methods
- {{domxref('CSSUnparsedValue.entries()')}}
- : Returns an array of a given object's own enumerable property `[key, value]` pairs in the same order as that provided by a {{jsxref("Statements/for...in", "for...in")}} loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
- {{domxref('CSSUnparsedValue.forEach()')}}
- : Executes a provided function once for each element of the `CSSUnparsedValue` object.
- {{domxref('CSSUnparsedValue.keys()')}}
- : Returns a new _array iterator_ object that contains the keys for each index in the `CSSUnparsedValue` object.
- {{domxref('CSSUnparsedValue.values()')}}
- : Returns a new _array iterator_ object that contains the values for each index in the `CSSUnparsedValue` object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref('CSSImageValue')}}
- {{domxref('CSSKeywordValue')}}
- {{domxref('CSSNumericValue')}}
- {{domxref('CSSPositionValue')}}
- {{domxref('CSSTransformValue')}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api/cssunparsedvalue | data/mdn-content/files/en-us/web/api/cssunparsedvalue/length/index.md | ---
title: "CSSUnparsedValue: length property"
short-title: length
slug: Web/API/CSSUnparsedValue/length
page-type: web-api-instance-property
browser-compat: api.CSSUnparsedValue.length
---
{{APIRef("CSS Typed OM")}}
The **`length`** read-only property of the
{{domxref("CSSUnparsedValue")}} interface returns the number of items in the object.
## Value
An integer.
## Examples
In this example we employ the {{domxref("CSSUnparsedValue.CSSUnparsedValue", "CSSUnparsedValue()")}}
constructor, then query the length:
```js
const values = new CSSUnparsedValue(["1em", "#445566", "-45px"]);
console.log(values.length); // 3
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CSSUnparsedValue.CSSUnparsedValue", "CSSUnparsedValue()")}}
- {{domxref("CSSUnparsedValue.entries")}}
- {{domxref("CSSUnparsedValue.forEach")}}
- {{domxref("CSSUnparsedValue.keys")}}
- {{domxref("CSSUnparsedValue.values")}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api/cssunparsedvalue | data/mdn-content/files/en-us/web/api/cssunparsedvalue/keys/index.md | ---
title: "CSSUnparsedValue: keys() method"
short-title: keys()
slug: Web/API/CSSUnparsedValue/keys
page-type: web-api-instance-method
browser-compat: api.CSSUnparsedValue.keys
---
{{APIRef("CSS Typed OM")}}
The **`CSSUnparsedValue.keys()`** method
returns a new _array iterator_ object that contains the keys
for each index in the array.
## Syntax
```js-nolint
keys()
```
### Parameters
None.
### Return value
A new {{jsxref("Array")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CSSUnparsedValue.CSSUnparsedValue", "CSSUnparsedValue()")}}
- {{domxref("CSSUnparsedValue.entries")}}
- {{domxref("CSSUnparsedValue.forEach")}}
- {{domxref("CSSUnparsedValue.length")}}
- {{domxref("CSSUnparsedValue.values")}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api/cssunparsedvalue | data/mdn-content/files/en-us/web/api/cssunparsedvalue/values/index.md | ---
title: "CSSUnparsedValue: values() method"
short-title: values()
slug: Web/API/CSSUnparsedValue/values
page-type: web-api-instance-method
browser-compat: api.CSSUnparsedValue.values
---
{{APIRef("CSS Typed OM")}}
The **`CSSUnparsedValue.values()`** method
returns a new _array iterator_ object that contains the
values for each index in the CSSUnparsedValue object.
## Syntax
```js-nolint
values()
```
### Parameters
None.
### Return value
A new {{jsxref("Array")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CSSUnparsedValue.CSSUnparsedValue", "CSSUnparsedValue()")}}
- {{domxref("CSSUnparsedValue.entries")}}
- {{domxref("CSSUnparsedValue.forEach")}}
- {{domxref("CSSUnparsedValue.keys")}}
- {{domxref("CSSUnparsedValue.length")}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api/cssunparsedvalue | data/mdn-content/files/en-us/web/api/cssunparsedvalue/cssunparsedvalue/index.md | ---
title: "CSSUnparsedValue: CSSUnparsedValue() constructor"
short-title: CSSUnparsedValue()
slug: Web/API/CSSUnparsedValue/CSSUnparsedValue
page-type: web-api-constructor
browser-compat: api.CSSUnparsedValue.CSSUnparsedValue
---
{{APIRef("CSS Typed OM")}}
The **`CSSUnparsedValue()`** constructor
creates a new {{domxref("CSSUnparsedValue")}} object which represents property values
that reference custom properties.
## Syntax
```js-nolint
new CSSUnparsedValue(members)
```
### Parameters
- `members`
- : An array whose values must be either a string or a
{{domxref('CSSVariableReferenceValue')}}.
## Examples
```js
const value = new CSSUnparsedValue(["4deg"]);
const values = new CSSUnparsedValue(["1em", "#445566", "-45px"]);
console.log(value); // CSSUnparsedValue {0: "4deg", length: 1}
console.log(values); // CSSUnparsedValue {0: "1em", 1: "#445566", 2: "-45px", length: 3}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CSSUnparsedValue.entries")}}
- {{domxref("CSSUnparsedValue.forEach")}}
- {{domxref("CSSUnparsedValue.keys")}}
- {{domxref("CSSUnparsedValue.length")}}
- {{domxref("CSSUnparsedValue.values")}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api/cssunparsedvalue | data/mdn-content/files/en-us/web/api/cssunparsedvalue/foreach/index.md | ---
title: "CSSUnparsedValue: forEach() method"
short-title: forEach()
slug: Web/API/CSSUnparsedValue/forEach
page-type: web-api-instance-method
browser-compat: api.CSSUnparsedValue.forEach
---
{{APIRef("CSS Typed OM")}}
The **`CSSUnparsedValue.forEach()`** method
executes a provided function once for each element of the
{{domxref('CSSUnparsedValue')}}.
## Syntax
```js-nolint
forEach(callbackFn)
forEach(callbackFn, thisArg)
```
### Parameters
- `callbackFn`
- : The function to execute for each element, taking three arguments:
- `currentValue`
- : The value of the current element being processed.
- `index` {{optional_inline}}
- : The index of the current element being processed.
- `array` {{optional_inline}}
- : The `CSSUnparsedValue` that `forEach()` is being called
on.
- `thisArg` {{Optional_inline}}
- : Value to use as **`this`** (i.e., the reference
`Object`) when executing `callback`.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CSSUnparsedValue.CSSUnparsedValue", "CSSUnparsedValue()")}}
- {{domxref("CSSUnparsedValue.entries")}}
- {{domxref("CSSUnparsedValue.keys")}}
- {{domxref("CSSUnparsedValue.length")}}
- {{domxref("CSSUnparsedValue.values")}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api/cssunparsedvalue | data/mdn-content/files/en-us/web/api/cssunparsedvalue/entries/index.md | ---
title: "CSSUnparsedValue: entries() method"
short-title: entries()
slug: Web/API/CSSUnparsedValue/entries
page-type: web-api-instance-method
browser-compat: api.CSSUnparsedValue.entries
---
{{APIRef("CSS Typed OM")}}
The **`CSSUnparsedValue.entries()`** method
returns an array of a given object's own enumerable property `[key, value]`
pairs in the same order as that provided by a {{jsxref("Statements/for...in",
"for...in")}} loop (the difference being that a for-in loop enumerates properties in the
prototype chain as well).
## Syntax
```js-nolint
entries(obj)
```
### Parameters
- `obj`
- : The {{domxref('CSSUnparsedValue')}} whose enumerable own property
`[key, value]` pairs are to be returned.
### Return value
An array of the given `CSSUnparsedValue` object's own enumerable property
`[key, value]` pairs.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CSSUnparsedValue.CSSUnparsedValue", "CSSUnparsedValue()")}}
- {{domxref("CSSUnparsedValue.forEach")}}
- {{domxref("CSSUnparsedValue.keys")}}
- {{domxref("CSSUnparsedValue.length")}}
- {{domxref("CSSUnparsedValue.values")}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/readablestreamdefaultreader/index.md | ---
title: ReadableStreamDefaultReader
slug: Web/API/ReadableStreamDefaultReader
page-type: web-api-interface
browser-compat: api.ReadableStreamDefaultReader
---
{{APIRef("Streams")}}
The **`ReadableStreamDefaultReader`** interface of the [Streams API](/en-US/docs/Web/API/Streams_API) represents a default reader that can be used to read stream data supplied from a network (such as a fetch request).
A `ReadableStreamDefaultReader` can be used to read from a {{domxref("ReadableStream")}} that has an underlying source of any type (unlike a {{domxref("ReadableStreamBYOBReader")}}, which can only be used with readable streams that have an _underlying byte source_).
Note however that zero-copy transfer from an underlying source is only supported for underlying byte sources that autoallocate buffers.
In other words, the stream must have been [constructed](/en-US/docs/Web/API/ReadableStream/ReadableStream) specifying both [`type="bytes"`](/en-US/docs/Web/API/ReadableStream/ReadableStream#type) and [`autoAllocateChunkSize`](/en-US/docs/Web/API/ReadableStream/ReadableStream#autoallocatechunksize).
For any other underlying source, the stream will always satisfy read requests with data from internal queues.
## Constructor
- {{domxref("ReadableStreamDefaultReader.ReadableStreamDefaultReader", "ReadableStreamDefaultReader()")}}
- : Creates and returns a `ReadableStreamDefaultReader` object instance.
## Instance properties
- {{domxref("ReadableStreamDefaultReader.closed")}} {{ReadOnlyInline}}
- : Returns a {{jsxref("Promise")}} that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process.
## Instance methods
- {{domxref("ReadableStreamDefaultReader.cancel()")}}
- : Returns a {{jsxref("Promise")}} that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. The supplied `reason` argument will be given to the underlying source, which may or may not use it.
- {{domxref("ReadableStreamDefaultReader.read()")}}
- : Returns a promise providing access to the next chunk in the stream's internal queue.
- {{domxref("ReadableStreamDefaultReader.releaseLock()")}}
- : Releases the reader's lock on the stream.
## Examples
In the following example, an artificial {{domxref("Response")}} is created to stream HTML fragments fetched from another resource to the browser.
It demonstrates the usage of a {{domxref("ReadableStream")}} in combination with a {{jsxref("Uint8Array")}}.
```js
fetch("https://www.example.org/").then((response) => {
const reader = response.body.getReader();
const stream = new ReadableStream({
start(controller) {
// The following function handles each data chunk
function push() {
// "done" is a Boolean and value a "Uint8Array"
return reader.read().then(({ done, value }) => {
// Is there no more data to read?
if (done) {
// Tell the browser that we have finished sending data
controller.close();
return;
}
// Get the data and send it to the browser via the controller
controller.enqueue(value);
push();
});
}
push();
},
});
return new Response(stream, { headers: { "Content-Type": "text/html" } });
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Streams API concepts](/en-US/docs/Web/API/Streams_API)
- [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams)
- {{domxref("ReadableStream")}}
- [WHATWG Stream Visualizer](https://whatwg-stream-visualizer.glitch.me/), for a basic visualization of readable, writable, and transform streams.
- [Web-streams-polyfill](https://github.com/MattiasBuelens/web-streams-polyfill) or [sd-streams](https://github.com/stardazed/sd-streams) - polyfills
| 0 |
data/mdn-content/files/en-us/web/api/readablestreamdefaultreader | data/mdn-content/files/en-us/web/api/readablestreamdefaultreader/closed/index.md | ---
title: "ReadableStreamDefaultReader: closed property"
short-title: closed
slug: Web/API/ReadableStreamDefaultReader/closed
page-type: web-api-instance-property
browser-compat: api.ReadableStreamDefaultReader.closed
---
{{APIRef("Streams")}}
The **`closed`** read-only property of the
{{domxref("ReadableStreamDefaultReader")}} interface returns a
{{jsxref("Promise")}} that fulfills when the stream closes, or rejects if the
stream throws an error or the reader's lock is released. This property enables you
to write code that responds to an end to the streaming process.
## Value
A {{jsxref("Promise")}}.
## Examples
In this snippet, a previously-created reader is queried to see if the stream has been
closed. When it is closed, the promise fulfills and the message is logged to the
console.
```js
reader.closed.then(() => {
console.log("reader closed");
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStreamDefaultReader.ReadableStreamDefaultReader", "ReadableStreamDefaultReader()")}} constructor
- [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestreamdefaultreader | data/mdn-content/files/en-us/web/api/readablestreamdefaultreader/read/index.md | ---
title: "ReadableStreamDefaultReader: read() method"
short-title: read()
slug: Web/API/ReadableStreamDefaultReader/read
page-type: web-api-instance-method
browser-compat: api.ReadableStreamDefaultReader.read
---
{{APIRef("Streams")}}
The **`read()`** method of the {{domxref("ReadableStreamDefaultReader")}} interface returns a {{jsxref("Promise")}} providing access to the next chunk in the stream's internal queue.
## Syntax
```js-nolint
read()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}}, which fulfills/rejects with a result depending on the state of the stream.
The different possibilities are as follows:
- If a chunk is available, the promise will be fulfilled with an object of the form `{ value: theChunk, done: false }`.
- If the stream becomes closed, the promise will be fulfilled with an object of the form `{ value: undefined, done: true }`.
- If the stream becomes errored, the promise will be rejected with the relevant error.
### Exceptions
- {{jsxref("TypeError")}}
- : The source object is not a `ReadableStreamDefaultReader`, the stream has no owner, or {{domxref("ReadableStreamDefaultReader.releaseLock()")}} is called (when there's a pending read request).
## Examples
### Example 1 - simple example
This example shows the basic API usage, but doesn't try to deal with complications like stream chunks not ending on line boundaries for example.
In this example, `stream` is a previously-created custom `ReadableStream`.
It is read using a {{domxref("ReadableStreamDefaultReader")}} created using `getReader()`.
(see our [Simple random stream example](https://mdn.github.io/dom-examples/streams/simple-random-stream/) for the full code).
Each chunk is read sequentially and output to the UI as an array of UTF-8 bytes, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI.
```js
function fetchStream() {
const reader = stream.getReader();
let charsReceived = 0;
// read() returns a promise that fulfills
// when a value has been received
reader.read().then(function processText({ done, value }) {
// Result objects contain two properties:
// done - true if the stream has already given you all its data.
// value - some data. Always undefined when done is true.
if (done) {
console.log("Stream complete");
para.textContent = result;
return;
}
// value for fetch streams is a Uint8Array
charsReceived += value.length;
const chunk = value;
let listItem = document.createElement("li");
listItem.textContent = `Received ${charsReceived} characters so far. Current chunk = ${chunk}`;
list2.appendChild(listItem);
result += chunk;
// Read some more, and call this function again
return reader.read().then(processText);
});
}
```
### Example 2 - handling text line by line
This example shows how you might fetch a text file and handle it as a stream of text lines.
It deals with stream chunks not ending on line boundaries, and with converting from `Uint8Array` to strings.
```js
async function* makeTextFileLineIterator(fileURL) {
const utf8Decoder = new TextDecoder("utf-8");
let response = await fetch(fileURL);
let reader = response.body.getReader();
let { value: chunk, done: readerDone } = await reader.read();
chunk = chunk ? utf8Decoder.decode(chunk, { stream: true }) : "";
let re = /\r\n|\n|\r/gm;
let startIndex = 0;
for (;;) {
let result = re.exec(chunk);
if (!result) {
if (readerDone) {
break;
}
let remainder = chunk.substr(startIndex);
({ value: chunk, done: readerDone } = await reader.read());
chunk =
remainder + (chunk ? utf8Decoder.decode(chunk, { stream: true }) : "");
startIndex = re.lastIndex = 0;
continue;
}
yield chunk.substring(startIndex, result.index);
startIndex = re.lastIndex;
}
if (startIndex < chunk.length) {
// last line didn't end in a newline char
yield chunk.substr(startIndex);
}
}
for await (let line of makeTextFileLineIterator(urlOfFile)) {
processLine(line);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStreamDefaultReader.ReadableStreamDefaultReader", "ReadableStreamDefaultReader()")}} constructor
- [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestreamdefaultreader | data/mdn-content/files/en-us/web/api/readablestreamdefaultreader/cancel/index.md | ---
title: "ReadableStreamDefaultReader: cancel() method"
short-title: cancel()
slug: Web/API/ReadableStreamDefaultReader/cancel
page-type: web-api-instance-method
browser-compat: api.ReadableStreamDefaultReader.cancel
---
{{APIRef("Streams")}}
The **`cancel()`** method of the
{{domxref("ReadableStreamDefaultReader")}} interface returns a {{jsxref("Promise")}} that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer.
Cancel is used when you've completely finished with the stream and don't need any more
data from it, even if there are chunks enqueued waiting to be read. That data is lost
after cancel is called, and the stream is not readable any more. To read those chunks
still and not completely get rid of the stream, you'd use
{{domxref("ReadableStreamDefaultController.close()")}}.
> **Note:** If the reader is active, the
> `cancel()` method behaves the same as that for the associated stream
> ({{domxref("ReadableStream.cancel()")}}).
## Syntax
```js-nolint
cancel()
cancel(reason)
```
### Parameters
- `reason` {{optional_inline}}
- : A human-readable reason for the cancellation. This value may or may not be used.
### Return value
A {{jsxref("Promise")}}, which fulfills with the value given in the `reason`
parameter.
### Exceptions
- {{jsxref("TypeError")}}
- : The source object is not a `ReadableStreamDefaultReader`, or the stream
has no owner.
## Examples
In the following simple example, a previously-created custom
`ReadableStream` is read using a {{domxref("ReadableStreamDefaultReader")}}
created using `getReader()`. (this code is based on our [Simple random stream example](https://mdn.github.io/dom-examples/streams/simple-random-stream/)). Each chunk is read sequentially and output to the UI, until the
stream has finished being read, at which point we return out of the recursive function
and print the entire stream to another part of the UI.
When the stream is done (`if (done)`), we run `reader.cancel()`
to cancel the stream, signalling that we don't need to use it any more.
```js
function fetchStream() {
const reader = stream.getReader();
let charsReceived = 0;
// read() returns a promise that resolves
// when a value has been received
reader.read().then(function processText({ done, value }) {
// Result objects contain two properties:
// done - true if the stream has already given you all its data.
// value - some data. Always undefined when done is true.
if (done) {
console.log("Stream complete");
reader.cancel();
para.textContent = result;
return;
}
// value for fetch streams is a Uint8Array
charsReceived += value.length;
const chunk = value;
let listItem = document.createElement("li");
listItem.textContent = `Received ${charsReceived} characters so far. Current chunk = ${chunk}`;
list2.appendChild(listItem);
result += chunk;
// Read some more, and call this function again
return reader.read().then(processText);
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStreamDefaultReader.ReadableStreamDefaultReader", "ReadableStreamDefaultReader()")}} constructor
- [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestreamdefaultreader | data/mdn-content/files/en-us/web/api/readablestreamdefaultreader/readablestreamdefaultreader/index.md | ---
title: "ReadableStreamDefaultReader: ReadableStreamDefaultReader() constructor"
short-title: ReadableStreamDefaultReader()
slug: Web/API/ReadableStreamDefaultReader/ReadableStreamDefaultReader
page-type: web-api-constructor
browser-compat: api.ReadableStreamDefaultReader.ReadableStreamDefaultReader
---
{{APIRef("Streams")}}
The **`ReadableStreamDefaultReader()`**
constructor creates and returns a `ReadableStreamDefaultReader` object
instance.
> **Note:** You generally wouldn't use this constructor manually; instead,
> you'd use the {{domxref("ReadableStream.getReader()")}} method.
## Syntax
```js-nolint
new ReadableStreamDefaultReader(stream)
```
### Parameters
- `stream`
- : The {{domxref("ReadableStream")}} to be read.
### Return value
An instance of the {{domxref("ReadableStreamDefaultReader")}} object.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the supplied `stream` parameter is not a {{domxref("ReadableStream")}},
or it is already locked for reading by another reader.
## Examples
In the following simple example, a previously-created custom
`ReadableStream` is read using a {{domxref("ReadableStreamDefaultReader")}}
created using `getReader()`. (see our [Simple random stream example](https://mdn.github.io/dom-examples/streams/simple-random-stream/) for the full code). Each chunk is read sequentially and output to
the UI, until the stream has finished being read, at which point we return out of the
recursive function and print the entire stream to another part of the UI.
```js
function fetchStream() {
const reader = stream.getReader();
let charsReceived = 0;
// read() returns a promise that resolves
// when a value has been received
reader.read().then(function processText({ done, value }) {
// Result objects contain two properties:
// done - true if the stream has already given you all its data.
// value - some data. Always undefined when done is true.
if (done) {
console.log("Stream complete");
para.textContent = result;
return;
}
// value for fetch streams is a Uint8Array
charsReceived += value.length;
const chunk = value;
let listItem = document.createElement("li");
listItem.textContent = `Received ${charsReceived} characters so far. Current chunk = ${chunk}`;
list2.appendChild(listItem);
result += chunk;
// Read some more, and call this function again
return reader.read().then(processText);
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Streams API concepts](/en-US/docs/Web/API/Streams_API)
- [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams)
- {{domxref("ReadableStream")}}
- {{domxref("ReadableStreamDefaultController")}}
| 0 |
data/mdn-content/files/en-us/web/api/readablestreamdefaultreader | data/mdn-content/files/en-us/web/api/readablestreamdefaultreader/releaselock/index.md | ---
title: "ReadableStreamDefaultReader: releaseLock() method"
short-title: releaseLock()
slug: Web/API/ReadableStreamDefaultReader/releaseLock
page-type: web-api-instance-method
browser-compat: api.ReadableStreamDefaultReader.releaseLock
---
{{APIRef("Streams")}}
The **`releaseLock()`** method of the {{domxref("ReadableStreamDefaultReader")}} interface releases the reader's lock on the stream.
If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed.
If the reader's lock is released while it still has pending read requests then the promises returned by the reader's {{domxref("ReadableStreamDefaultReader.read()")}} method are immediately rejected with a `TypeError`.
Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader.
## Syntax
```js-nolint
releaseLock()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the source object is not a `ReadableStreamDefaultReader`.
## Examples
```js
function fetchStream() {
const reader = stream.getReader();
// ...
reader.releaseLock();
// ...
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("ReadableStreamDefaultReader.ReadableStreamDefaultReader", "ReadableStreamDefaultReader()")}} constructor
- [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcaudiosourcestats/index.md | ---
title: RTCAudioSourceStats
slug: Web/API/RTCAudioSourceStats
page-type: web-api-interface
browser-compat: api.RTCStatsReport.type_media-source
---
{{APIRef("WebRTC")}}
The [WebRTC API](/en-US/docs/Web/API/WebRTC_API)'s **`RTCAudioSourceStats`** dictionary provides information about an audio track that is attached to one or more senders.
These statistics can be obtained by iterating the {{domxref("RTCStatsReport")}} returned by {{domxref("RTCRtpSender.getStats()")}} or {{domxref("RTCPeerConnection.getStats()")}} until you find a report with the [`type`](#type) of `media-source` and a [`kind`](#kind) of `audio`.
> **Note:** For audio information about remotely sourced tracks (that are being received), see {{domxref("RTCInboundRtpStreamStats")}}.
## Instance properties
- {{domxref("RTCAudioSourceStats.audioLevel", "audioLevel")}} {{Experimental_Inline}}
- : A number that represents the audio level of the media source.
- {{domxref("RTCAudioSourceStats.totalAudioEnergy", "totalAudioEnergy")}} {{Experimental_Inline}}
- : A number that represents the total audio energy of the media source over the lifetime of the stats object.
- {{domxref("RTCAudioSourceStats.totalSamplesDuration", "totalSamplesDuration")}} {{Experimental_Inline}}
- : A number that represents the total duration of all samples produced by the media source over the lifetime of the stats object.
The following properties are present in both `RTCAudioSourceStats` and {{domxref("RTCVideoSourceStats")}}: <!-- RTCMediaSourceStats -->
- {{domxref("RTCAudioSourceStats.trackIdentifier", "trackIdentifier")}}
- : A string that contains the [`id`](/en-US/docs/Web/API/MediaStreamTrack/id) value of the [`MediaStreamTrack`](/en-US/docs/Web/API/MediaStreamTrack) associated with the audio source.
- {{domxref("RTCAudioSourceStats.kind", "kind")}}
- : A string indicating whether this object represents stats for a video source or a media source. For an `RTCAudioSourceStats` this will always be `audio`.
### Common instance properties
The following properties are common to all statistics objects. <!-- RTCStats -->
- {{domxref("RTCAudioSourceStats.id", "id")}}
- : A string that uniquely identifies the object that is being monitored to produce this set of statistics.
- {{domxref("RTCAudioSourceStats.timestamp", "timestamp")}}
- : A {{domxref("DOMHighResTimeStamp")}} object indicating the time at which the sample was taken for this statistics object.
- {{domxref("RTCAudioSourceStats.type", "type")}}
- : A string with the value `"media-source"`, indicating that the object is an instance of either {{domxref("RTCAudioSourceStats")}} or {{domxref("RTCVideoSourceStats")}}.
## Description
The interface provides statistics about an audio media source attached to one or more senders.
The information includes the current audio level, averaged over a short (implementation dependent) duration.
The statistics also include the accumulated total energy and total sample duration, at a particular timestamp.
The totals can be used to determine the average audio level over the lifetime of the stats object.
You can calculate a root mean square (RMS) value in the same units as `audioLevel` using the following formula:
<math display="block">
<msqrt>
<mfrac>
<mi>totalAudioEnergy</mi>
<mi>totalSamplesDuration</mi>
</mfrac>
</msqrt>
</math>
You can also use the accumulated totals to calculate the average audio level over an arbitrary time period.
The total audio energy of the stats object is accumulated by adding the energy of every sample over the lifetime of the stats object, while the total duration is accumulated by adding the duration of each sample.
The energy of each sample is determined using the following formula, where `sample_level` is the level of the sample, `max_level` is the highest-intensity encodable value, and `duration` is the duration of the sample in seconds:
<math display="block">
<mrow>
<mi>duration</mi>
<mo>⁢</mo>
<msup>
<mrow>
<mo>(</mo>
<mfrac>
<mi>sample_level</mi>
<mi>max_level</mi>
</mfrac>
<mo>)</mo>
</mrow>
<mn>2</mn>
</msup>
</mrow>
</math>
The average audio level between any two different `getStats()` calls, over any duration, can be calculated using the following equation:
<math display="block">
<msqrt>
<mfrac>
<mrow>
<msub>
<mi>totalAudioEnergy</mi>
<mn>2</mn>
</msub>
<mo>-</mo>
<msub>
<mi>totalAudioEnergy</mi>
<mn>1</mn>
</msub>
</mrow>
<mrow>
<msub>
<mi>totalSamplesDuration</mi>
<mn>2</mn>
</msub>
<mo>-</mo>
<msub>
<mi>totalSamplesDuration</mi>
<mn>1</mn>
</msub>
</mrow>
</mfrac>
</msqrt>
</math>
## Examples
This example shows how you might iterate the stats object returned from `RTCRtpSender.getStats()` to get the audio source stats, and then extract the `audioLevel`.
```js
// where sender is an RTCRtpSender
const stats = await sender.getStats();
let audioSourceStats = null;
stats.forEach((report) => {
if (report.type === "media-source" && report.kind==="audio") {
audioSourceStats = report;
break;
}
});
const audioLevel = audioSourceStats?.audioLevel;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcaudiosourcestats | data/mdn-content/files/en-us/web/api/rtcaudiosourcestats/trackidentifier/index.md | ---
title: "RTCAudioSourceStats: trackIdentifier property"
short-title: trackIdentifier
slug: Web/API/RTCAudioSourceStats/trackIdentifier
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_media-source.trackIdentifier
---
{{APIRef("WebRTC")}}
The {{domxref("RTCAudioSourceStats")}} dictionary's property **`trackIdentifier`** contains the `id` attribute of the associated [`MediaStreamTrack`](/en-US/docs/Web/API/MediaStreamTrack).
## Value
A string containing the value of the associated [`MediaStreamTrack.id`](/en-US/docs/Web/API/MediaStreamTrack/id).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcaudiosourcestats | data/mdn-content/files/en-us/web/api/rtcaudiosourcestats/totalsamplesduration/index.md | ---
title: "RTCAudioSourceStats: totalSamplesDuration property"
short-title: totalSamplesDuration
slug: Web/API/RTCAudioSourceStats/totalSamplesDuration
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.RTCStatsReport.type_media-source.totalSamplesDuration
---
{{APIRef("WebRTC")}}{{SeeCompatTable}}
The {{domxref("RTCAudioSourceStats")}} dictionary's **`totalSamplesDuration`** property represents the combined duration of all samples produced by the media source over the lifetime of this stats object, in seconds.
It does not include samples dropped before reaching this media source. <!-- Dropped samples in `droppedSamplesDuration`; not implemented -->
This can be used with {{domxref("RTCAudioSourceStats.totalAudioEnergy", "totalAudioEnergy")}} to compute an [average audio level over different intervals](/en-US/docs/Web/API/RTCAudioSourceStats#description).
> **Note:** For audio duration of remotely sourced tracks, see {{domxref("RTCInboundRtpStreamStats.totalSamplesDuration")}}.
## Value
A number indicating the total duration of all samples produced by this source over the lifetime this stats object, in seconds.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcaudiosourcestats | data/mdn-content/files/en-us/web/api/rtcaudiosourcestats/totalaudioenergy/index.md | ---
title: "RTCAudioSourceStats: totalAudioEnergy property"
short-title: totalAudioEnergy
slug: Web/API/RTCAudioSourceStats/totalAudioEnergy
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.RTCStatsReport.type_media-source.totalAudioEnergy
---
{{APIRef("WebRTC")}}{{SeeCompatTable}}
The {{domxref("RTCAudioSourceStats")}} dictionary's **`totalAudioEnergy`** property represents the total audio energy of the media source over the lifetime of this stats object.
The total energy across a particular duration can be determined by subtracting the value of this property returned by two different `getStats()` calls.
> **Note:** For audio energy of remotely sourced tracks, see {{domxref("RTCInboundRtpStreamStats.totalAudioEnergy")}}.
## Value
A number produced by summing the energy of every sample over the lifetime of this stats object.
The energy of each sample is calculated by dividing the sample's value by the highest-intensity encodable value, squaring the result, and then multiplying by the duration of the sample in seconds.
This is shown as an equation below:
<math display="block">
<mrow>
<mi>duration</mi>
<mo>⁢</mo>
<msup>
<mrow>
<mo>(</mo>
<mfrac>
<mi>sample_level</mi>
<mi>max_level</mi>
</mfrac>
<mo>)</mo>
</mrow>
<mn>2</mn>
</msup>
</mrow>
</math>
Note that if multiple audio channels are used, the audio energy of a sample refers to the highest energy of any channel.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcaudiosourcestats | data/mdn-content/files/en-us/web/api/rtcaudiosourcestats/id/index.md | ---
title: "RTCAudioSourceStats: id property"
short-title: id
slug: Web/API/RTCAudioSourceStats/id
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_media-source.id
---
{{APIRef("WebRTC")}}
The **`id`** property of the {{domxref("RTCAudioSourceStats")}} dictionary is a string which uniquely identifies the object for which this object provides statistics.
Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an {{domxref("RTCPeerConnection")}}, or an {{domxref("RTCDataChannel")}}.
## Value
A string that uniquely identifies the object for which this `RTCAudioSourceStats` object provides statistics.
The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcaudiosourcestats | data/mdn-content/files/en-us/web/api/rtcaudiosourcestats/type/index.md | ---
title: "RTCAudioSourceStats: type property"
short-title: type
slug: Web/API/RTCAudioSourceStats/type
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_media-source.type
---
{{APIRef("WebRTC")}}
The {{domxref("RTCAudioSourceStats")}} dictionary's property **`type`** is a string with value `media-source`.
The type of `media-source` identifies the type of statistics as either {{domxref("RTCAudioSourceStats")}} or {{domxref("RTCVideoSourceStats")}} when iterating the {{domxref("RTCStatsReport")}} returned by {{domxref("RTCRtpSender.getStats()")}} or {{domxref("RTCPeerConnection.getStats()")}}.
The type of stats can further be differentiated using the {{domxref("RTCAudioSourceStats.kind", "kind")}}, which will be `audio` for `RTCAudioSourceStats`.
## Value
A string with the value `media-source`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcaudiosourcestats | data/mdn-content/files/en-us/web/api/rtcaudiosourcestats/timestamp/index.md | ---
title: "RTCAudioSourceStats: timestamp property"
short-title: timestamp
slug: Web/API/RTCAudioSourceStats/timestamp
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_media-source.timestamp
---
{{APIRef("WebRTC")}}
The **`timestamp`** property of the {{domxref("RTCAudioSourceStats")}} dictionary is a {{domxref("DOMHighResTimeStamp")}} object specifying the time at which the data in the object was sampled.
The time is given in milliseconds elapsed since the first moment of January 1, 1970, UTC (also known as [Unix time](/en-US/docs/Glossary/Unix_time)).
## Value
A {{domxref("DOMHighResTimeStamp")}} value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC.
The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of [fingerprinting](/en-US/docs/Glossary/Fingerprinting) protection in the form of reduced clock precision or accuracy.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcaudiosourcestats | data/mdn-content/files/en-us/web/api/rtcaudiosourcestats/kind/index.md | ---
title: "RTCAudioSourceStats: kind property"
short-title: kind
slug: Web/API/RTCAudioSourceStats/kind
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.type_media-source.kind
---
{{APIRef("WebRTC")}}
The {{domxref("RTCAudioSourceStats")}} dictionary's **`kind`** property is a string value that is used to differentiate `audio` and `video` media sources.
Along with the {{domxref("RTCAudioSourceStats.type", "type")}}, this identifies the object as an {{domxref("RTCAudioSourceStats")}} object when iterating the {{domxref("RTCStatsReport")}} returned by {{domxref("RTCRtpSender.getStats()")}} or {{domxref("RTCPeerConnection.getStats()")}}.
## Value
A string with the value `audio`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcaudiosourcestats | data/mdn-content/files/en-us/web/api/rtcaudiosourcestats/audiolevel/index.md | ---
title: "RTCAudioSourceStats: audioLevel property"
short-title: audioLevel
slug: Web/API/RTCAudioSourceStats/audioLevel
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.RTCStatsReport.type_media-source.audioLevel
---
{{APIRef("WebRTC")}}{{SeeCompatTable}}
The {{domxref("RTCAudioSourceStats")}} dictionary's **`audioLevel`** property represents the audio level of the media source.
The level is averaged over some small implementation-dependent interval.
Users can alternatively calculate the average audio level over some arbitrary duration using the algorithm described in the [`RTCAudioSourceStats` description](/en-US/docs/Web/API/RTCAudioSourceStats#description).
> **Note:** For audio levels of remotely sourced tracks, see {{domxref("RTCInboundRtpStreamStats.audioLevel")}}.
## Value
A number between 0 and 1 (linear), where 1.0 represents 0 dBov ([decibels relative to full scale (DBFS)](https://en.wikipedia.org/wiki/DBFS)), 0 represents silence, and 0.5 represents approximately 6 dB SPL change in the [sound pressure level](https://en.wikipedia.org/wiki/Sound_pressure#Sound_pressure_level) from 0 dBov.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcstatsreport/index.md | ---
title: RTCStatsReport
slug: Web/API/RTCStatsReport
page-type: web-api-interface
browser-compat: api.RTCStatsReport
---
{{APIRef("WebRTC")}}
The **`RTCStatsReport`** interface of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) provides a statistics report for a {{domxref("RTCPeerConnection")}}, {{domxref("RTCRtpSender")}}, or {{domxref("RTCRtpReceiver")}}.
An `RTCStatsReport` instance is a read-only [`Map`-like object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#map-like_browser_apis), in which each key is an identifier for an object for which statistics are being reported, and the corresponding value is a dictionary object providing the statistics.
## Instance properties
- {{domxref("RTCStatsReport.size")}}
- : Returns the number of items in the `RTCStatsReport` object.
## Instance methods
- {{domxref("RTCStatsReport.entries()")}}
- : Returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains a two-member array of `[id, statistic-dictionary]` for each element in the `RTCStatsReport` object, in insertion order.
- {{domxref("RTCStatsReport.forEach()")}}
- : Calls `callbackFn` once for each key-value pair present in the `RTCStatsReport` object, in insertion order.
If a `thisArg` parameter is provided to `forEach`, it will be used as the `this` value for each callback.
- {{domxref("RTCStatsReport.get()")}}
- : Returns the statistics dictionary associated with the passed `id`, or `undefined` if there is none.
- {{domxref("RTCStatsReport.has()")}}
- : Returns a boolean indicating whether the `RTCStatsReport` contains a statistics dictionary associated with the specified `id`.
- {{domxref("RTCStatsReport.keys()")}}
- : Returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains the keys (IDs) for each element in the `RTCStatsReport` object, in insertion order.
- {{domxref("RTCStatsReport.values()")}}
- : Returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains the values (statistics object) for each element in the `RTCStatsReport` object, in insertion order.
- [`RTCStatsReport.[@@iterator]()`](/en-US/docs/Web/API/RTCStatsReport/@@iterator)
- : Returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains a two-member array of `[id, statistic-dictionary]` for each element in the `RTCStatsReport` object, in insertion order.
## Description
A {{jsxref("Promise")}} that resolves to an `RTCStatsReport` is returned from the {{domxref("RTCRtpReceiver.getStats()")}}, {{domxref("RTCRtpSender.getStats()")}} and {{domxref("RTCPeerConnection.getStats()")}} methods.
Calling `getStats()` on an {{domxref("RTCPeerConnection")}} lets you specify whether you wish to obtain outbound statistics, inbound statistics, or statistics for the whole connection.
The {{domxref("RTCRtpReceiver")}} and {{domxref("RTCRtpSender")}} versions of `getStats()` only return inbound and outbound statistics, respectively.
The statistics report is a read-only [`Map`-like](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) object: an ordered dictionary, where the properties are `id` strings that uniquely identify the WebRTC object that was inspected to produce a particular set of statistics, and the value is a dictionary object containing those statistics.
A `RTCStatsReport` can be iterated and used the same ways as a read-only `Map`.
The report may contain many different categories of statistics, including inbound and outbound statistics for both the current and remote ends of the peer connection, information about codecs, certificates and media used, and so on.
Each category of statistic is provided in a different type of statistics dictionary object, which can be identified from its [`type`](#type) property.
### Common instance properties
All the dictionary types have the following properties:
- `id`
- : A string that uniquely identifies the object was monitored to produce the set of statistics.
This value persists across reports for (at least) the lifetime of the connection.
Note however that for some statistics the ID may vary between browsers and for subsequent connections, even to the same peer.
- `timestamp`
- : A high resolution timestamp object ({{domxref("DOMHighResTimeStamp")}}) object indicating the time at which the sample was taken.
Many reported statistics are cumulative values; the timestamp allows rates and averages to be calculated between any two reports, at any desired reporting rate.
- `type`
- : A string with a value that indicates the type of statistics that the object contains, such as `candidate-pair`, `inbound-rtp`, `certificate`, and so on.
The [types of statistics and their corresponding objects](#the_statistic_types) are listed below.
Users typically iterate a `RTCStatsReport`, using a {{domxref("RTCStatsReport.forEach()", "forEach()")}} or [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop, selecting the statistics of interest using the `type` property.
Once a particular statistic object has been identified using its `type`, the `id` property can subsequently be used with {{domxref("RTCStatsReport.get()", "get()")}} to obtain the same statistic report at a different time.
The timestamp can be used to calculate average values for statistics that accumulate over the lifetime of a connection.
### The statistic types
The statistics `type` values and their corresponding dictionaries are listed below.
| type | Dictionary | Description |
| --------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `candidate-pair` | {{domxref("RTCIceCandidatePairStats")}} | Statistics describing the change from one {{domxref("RTCIceTransport")}} to another, such as during an [ICE restart](/en-US/docs/Web/API/WebRTC_API/Session_lifetime#ice_restart). |
| `certificate` | {{domxref("RTCCertificateStats")}} | Statistics about a certificate being used by an {{domxref("RTCIceTransport")}}. |
| `codec` | {{domxref("RTCCodecStats")}} | Statistics about a specific codec being used by streams being sent or received by this connection. |
| `data-channel` | {{domxref("RTCDataChannelStats")}} | Statistics related to one {{domxref("RTCDataChannel")}} on the connection. |
| `inbound-rtp` | {{domxref("RTCInboundRtpStreamStats")}} | Statistics describing the state of one of the connection's inbound data streams. |
| `local-candidate` | {{domxref("RTCIceCandidateStats")}} | Statistics about a local ICE candidate associated with the connection's {{domxref("RTCIceTransport")}}s. |
| `media-source` | {{domxref("RTCAudioSourceStats")}} or {{domxref("RTCVideoSourceStats")}} | Statistics about the media produced by the {{domxref("MediaStreamTrack")}} attached to an RTP sender. The dictionary this key maps to depends on the track's {{domxref("MediaStreamTrack.kind", "kind")}}. |
| `outbound-rtp` | {{domxref("RTCOutboundRtpStreamStats")}} | Statistics describing the state of one of the outbound data streams on this connection. |
| `peer-connection` | {{domxref("RTCPeerConnectionStats")}} | Statistics describing the state of the {{domxref("RTCPeerConnection")}}. |
| `remote-candidate` | {{domxref("RTCIceCandidateStats")}} | Statistics about a remote ICE candidate associated with the connection's {{domxref("RTCIceTransport")}}s. |
| `remote-inbound-rtp` | {{domxref("RTCRemoteInboundRtpStreamStats")}} | Statistics describing the state of the inbound data stream from the perspective of the remote peer. |
| `remote-outbound-rtp` | {{domxref("RTCRemoteOutboundRtpStreamStats")}} | Statistics describing the state of the outbound data stream from the perspective of the remote peer. |
| `transport` | {{domxref("RTCTransportStats")}} | Statistics about a transport used by the connection. |
## Examples
### Iterate report from an RTCPeerConnection using forEach loop
This example logs shows how you might log video-related statistics for the local {{domxref("RTCRtpReceiver")}} responsible for receiving streamed media.
Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code uses `await` to wait for the statistics report, and then iterates it using {{domxref("RTCStatsReport.forEach()")}}.
It then filters the dictionaries for just those reports that have the `type` of `inbound-rtp` and `kind` of `video`.
```js
const stats = await myPeerConnection.getStats();
stats.forEach((report) => {
if (report.type === "inbound-rtp" && report.kind === "video") {
// Log the frame rate
console.log(report.framesPerSecond);
}
});
```
### Iterate report from an RTCRtpSender using a for...of loop
This example shows how you might iterate the outbound statistics from an {{domxref("RTCRtpSender")}}.
The code follows a similar pattern to the previous example, but iterates using a `for...of`-loop on the {{domxref("RTCStatsReport.values()")}}, and filters on the `type` of `outbound-rtp`.
It assumes you already have an `RTCRtpSender` object named "sender".
```js
const stats = await sender.getStats();
for (const stat of stats.values()) {
if (stat.type != "outbound-rtp") continue;
Object.keys(stat).forEach((statName) => {
console.log(`${statName}: ${report[statName]}`);
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
- {{domxref("RTCPeerConnection")}}
- {{domxref("RTCPeerConnection.getStats()")}}, {{domxref("RTCRtpReceiver.getStats()")}}, and {{domxref("RTCRtpSender.getStats()")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcstatsreport | data/mdn-content/files/en-us/web/api/rtcstatsreport/get/index.md | ---
title: "RTCStatsReport: get() method"
short-title: get()
slug: Web/API/RTCStatsReport/get
page-type: web-api-instance-method
browser-compat: api.RTCStatsReport.get
---
{{APIRef("WebRTC")}}
The **`get()`** method of the {{domxref("RTCStatsReport")}} interface returns a specified element from an `RTCStatsReport`.
Elements in the `RTCStatsReport` are identified by unique `id` values, which represent the monitored statistics objects from which the statistics are derived.
The element returned will be an instance of one of the [statistics dictionary objects](/en-US/docs/Web/API/RTCStatsReport#the_statistic_types), and it will contain statistics for the object with the given `id`.
The fetched value is a reference to the statistics dictionary, and any change made to that object will effectively modify it inside the `RTCStatsReport` object.
The method is otherwise the same as {{jsxref("Map.prototype.get()")}}.
## Syntax
```js-nolint
get(id)
```
### Parameters
- `id`
- : A string indicating the ID of the element to return from the `RTCStatsReport` object.
IDs are unique strings that identify the monitored object from which the corresponding statistics are derived.
### Return value
The element associated with the specified `id` key, or {{jsxref("undefined")}} if the key can't be found in the `Map` object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map.prototype.get()")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcstatsreport | data/mdn-content/files/en-us/web/api/rtcstatsreport/has/index.md | ---
title: "RTCStatsReport: has() method"
short-title: has()
slug: Web/API/RTCStatsReport/has
page-type: web-api-instance-method
browser-compat: api.RTCStatsReport.has
---
{{APIRef("WebRTC")}}
The **`has()`** method of the {{domxref("RTCStatsReport")}} interface returns a boolean indicating whether a report contains a statistics dictionary with the specified id.
The method is otherwise the same as {{jsxref("Map.prototype.has()")}}.
## Syntax
```js-nolint
has(id)
```
### Parameters
- `id`
- : A string containing the ID of a statistics object that might be present in this `RTCStatsReport`.
### Return value
`true` if an element with the specified `id` exists in the `RTCStatsReport` object; otherwise `false`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map")}}
- {{jsxref("Map.prototype.set()")}}
- {{jsxref("Map.prototype.get()")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcstatsreport | data/mdn-content/files/en-us/web/api/rtcstatsreport/keys/index.md | ---
title: "RTCStatsReport: keys() method"
short-title: keys()
slug: Web/API/RTCStatsReport/keys
page-type: web-api-instance-method
browser-compat: api.RTCStatsReport.keys
---
{{APIRef("WebRTC")}}
The **`keys()`** method of the {{domxref("RTCStatsReport")}} interface returns a new _[iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that can be used to iterate through the keys for each element in the `RTCStatsReport` object, in insertion order.
The keys in the `RTCStatsReport` are unique string `id` values, which represent the monitored statistics objects from which the statistics are derived.
The method is otherwise the same as {{jsxref("Map.prototype.keys()")}}.
## Syntax
```js-nolint
keys()
```
### Return value
A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator).
## Examples
This example shows how to iterate through a {{domxref("RTCStatsReport")}} using the iterator returned by `keys()`.
Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code calls [`getStats()`](/en-US/docs/Web/API/RTCRtpReceiver/getStats) with `await` to wait for the statistics report.
It then uses a [for...of](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop, with the iterator returned by `keys()`, to iterate through the IDs.
Each ID is used to get the corresponding statistics dictionary.
The properties of statistics objects with the `type` of `outbound-rtp` are logged to the console (other objects are discarded).
```js
const stats = await myPeerConnection.getStats();
for (const id of stats.keys()) {
// Get dictionary associated with key (id)
const stat = stats.get(id);
if (stat.type != "outbound-rtp") continue;
Object.keys(stat).forEach((statName) => {
console.log(`${statName}: ${report[statName]}`);
});
}
```
Note that this examples is somewhat contrived.
You could more easily iterate with {{domxref("RTCStatsReport.entries()","entries()")}} or {{domxref("RTCStatsReport.values()","values()")}} and not have to map the ID to a value.
You can even iterate the {{domxref("RTCStatsReport")}} itself, as it has the [`@@iterator`](/en-US/docs/Web/API/RTCStatsReport/@@iterator) method!
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map.prototype.keys()")}}
- {{domxref("RTCStatsReport.values()")}}
- {{domxref("RTCStatsReport.entries()")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcstatsreport | data/mdn-content/files/en-us/web/api/rtcstatsreport/size/index.md | ---
title: "RTCStatsReport: size property"
short-title: size
slug: Web/API/RTCStatsReport/size
page-type: web-api-instance-property
browser-compat: api.RTCStatsReport.size
---
{{APIRef("WebRTC")}}
The **`size`** read-only property of the {{domxref("RTCStatsReport")}} interface returns the number of items in the current report.
Note that each item consists of a key-value pair, where the keys are unique `id` values for monitored statistics objects from which the statistics are derived, and the associated values are [statistics dictionary objects](/en-US/docs/Web/API/RTCStatsReport#the_statistic_types).
This property is otherwise the same as {{jsxref("Map.prototype.size")}}.
## Value
An integer indicating the number of items in this report.
The value is zero if the report is empty.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcstatsreport | data/mdn-content/files/en-us/web/api/rtcstatsreport/values/index.md | ---
title: "RTCStatsReport: values() method"
short-title: values()
slug: Web/API/RTCStatsReport/values
page-type: web-api-instance-method
browser-compat: api.RTCStatsReport.values
---
{{APIRef("WebRTC")}}
The **`values()`** method of the {{domxref("RTCStatsReport")}} interface returns a new _[iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that can be used to iterate through the values for each element in the `RTCStatsReport` object, in insertion order.
The values are [statistics dictionary objects](/en-US/docs/Web/API/RTCStatsReport#the_statistic_types).
The method is otherwise the same as {{jsxref("Map.prototype.values()")}}.
## Syntax
```js-nolint
values()
```
### Return value
A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator).
## Examples
This example shows how to iterate through a {{domxref("RTCStatsReport")}} using the iterator returned by `values()`.
Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code calls [`getStats()`](/en-US/docs/Web/API/RTCRtpReceiver/getStats) with `await` to wait for the statistics report.
It then uses a [for...of](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop, with the iterator returned by `values()`, to iterate through the dictionary objects in the report.
The properties of statistics objects with the `type` of `outbound-rtp` are logged to the console (other objects are discarded).
```js
const stats = await myPeerConnection.getStats();
for (const stat of stats.values()) {
if (stat.type != "outbound-rtp") continue;
Object.keys(stat).forEach((statName) => {
console.log(`${statName}: ${report[statName]}`);
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map.prototype.values()")}}
- {{domxref("RTCStatsReport.keys()")}}
- {{domxref("RTCStatsReport.entries()")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcstatsreport | data/mdn-content/files/en-us/web/api/rtcstatsreport/@@iterator/index.md | ---
title: "RTCStatsReport: [@@iterator]() method"
short-title: "@@iterator"
slug: Web/API/RTCStatsReport/@@iterator
page-type: web-api-instance-method
browser-compat: api.RTCStatsReport.@@iterator
---
{{APIRef("WebRTC")}}
The **`[@@iterator]()`** method of the {{domxref("RTCStatsReport")}} interface implements the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) and allows statistics reports to be consumed by most syntaxes expecting iterables, such as the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and {{jsxref("Statements/for...of", "for...of")}} loops.
It returns an [iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the key-value pairs of the report in insertion order.
The initial value of this property is the same function object as the initial value of the {{domxref("RTCStatsReport.entries()")}} method.
The method is otherwise the same as [`Map.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator).
## Syntax
```js-nolint
RTCStatsReport[Symbol.iterator]()
```
### Return value
The same return value as {{domxref("RTCStatsReport.entries()")}}.
This is a new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the key-value (`id`-"statistics dictionary") pairs of the report.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("RTCStatsReport.entries()")}}
- [`Map.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator)
| 0 |
data/mdn-content/files/en-us/web/api/rtcstatsreport | data/mdn-content/files/en-us/web/api/rtcstatsreport/foreach/index.md | ---
title: "RTCStatsReport: forEach() method"
short-title: forEach()
slug: Web/API/RTCStatsReport/forEach
page-type: web-api-instance-method
browser-compat: api.RTCStatsReport.forEach
---
{{APIRef("WebRTC")}}
The **`forEach()`** method of the {{domxref("RTCStatsReport")}} interface executes a provided function once for each key/value pair in the `RTCStatsReport` object, in insertion order.
The keys are unique `id` values for the monitored statistics objects from which the statistics are derived, and the associated values are [statistics dictionary objects](/en-US/docs/Web/API/RTCStatsReport#the_statistic_types).
The method is otherwise the same as {{jsxref("Map.prototype.forEach()")}}.
## Syntax
```js-nolint
forEach(callbackFn)
forEach(callbackFn, thisArg)
```
### Parameters
- `callbackFn`
- : A function to execute for each entry in the report.
The function is called with the following arguments:
- `report`
- : Statistics report for each iteration.
This can be any of the [statistics dictionary types](/en-US/docs/Web/API/RTCStatsReport#the_statistic_types).
- `id`
- : A unique string identifying the monitored object from which the statistics are derived.
- `map`
- : The report being iterated.
- `thisArg` {{optional_inline}}
- : A value to use as `this` when executing `callbackFn`.
### Return value
{{jsxref("undefined")}}.
## Examples
Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code calls [`getStats()`](/en-US/docs/Web/API/RTCRtpReceiver/getStats) with `await` to wait for the statistics report.
It then iterates the report using {{domxref("RTCStatsReport.forEach()")}}, and filters the dictionaries for just those reports that have the `type` of `inbound-rtp` and `kind` of `video`.
For matching dictionaries it logs the `framesPerSecond` property of the inbound video.
```js
const stats = await myPeerConnection.getStats();
stats.forEach((report) => {
if (report.type === "inbound-rtp" && report.kind === "video") {
// Log the frame rate
console.log(report.framesPerSecond);
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map.prototype.forEach()")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcstatsreport | data/mdn-content/files/en-us/web/api/rtcstatsreport/entries/index.md | ---
title: "RTCStatsReport: entries() method"
short-title: entries()
slug: Web/API/RTCStatsReport/entries
page-type: web-api-instance-method
browser-compat: api.RTCStatsReport.entries
---
{{APIRef("WebRTC")}}
The **`entries()`** method of the {{domxref("RTCStatsReport")}} interface returns a new [iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that can be used to iterate through the key/value pairs for each element in the `RTCStatsReport` object, in insertion order.
The keys are unique `id` values for monitored statistics objects from which the statistics are derived, and the associated values are [statistics dictionary objects](/en-US/docs/Web/API/RTCStatsReport#the_statistic_types).
The method is otherwise the same as {{jsxref("Map.prototype.entries()")}}.
## Syntax
```js-nolint
entries()
```
### Parameters
None.
### Return value
A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator).
## Examples
This example shows how to iterate through a {{domxref("RTCStatsReport")}} using the iterator returned by `entries()`.
Given a variable `myPeerConnection`, which is an instance of `RTCPeerConnection`, the code calls [`getStats()`](/en-US/docs/Web/API/RTCRtpReceiver/getStats) with `await` to wait for the statistics report.
It then uses a [for...of](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop, with the iterator returned by `entries()`, to iterate through the entries.
The properties of statistics objects with the `type` of `outbound-rtp` are logged to the console (other objects are discarded).
```js
const stats = await myPeerConnection.getStats();
for (const stat of stats.entries()) {
if (stat.type != "outbound-rtp") continue;
Object.keys(stat).forEach((statName) => {
console.log(`${statName}: ${report[statName]}`);
});
}
```
## Specifications
{{Specifications}} <!-- https://webidl.spec.whatwg.org/#dfn-maplike -->
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map.prototype.entries()")}}
- {{domxref("RTCStatsReport.values()")}}
- {{domxref("RTCStatsReport.keys()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/interventionreportbody/index.md | ---
title: InterventionReportBody
slug: Web/API/InterventionReportBody
page-type: web-api-interface
status:
- experimental
browser-compat: api.InterventionReportBody
---
{{APIRef("Reporting API")}}{{SeeCompatTable}}
The `InterventionReportBody` interface of the [Reporting API](/en-US/docs/Web/API/Reporting_API) represents the body of an intervention report.
An intervention report is generated when usage of a feature in a web document has been blocked by the browser for reasons such as security, performance, or user annoyance. So for example, a script was been stopped because it was significantly slowing down the browser, or the browser's autoplay policy blocked audio from playing without a user gesture to trigger it.
A deprecation report is generated when a deprecated feature (for example a deprecated API method) is used on a document being observed by a {{domxref("ReportingObserver")}}. In addition to the support of this API, receiving useful intervention warnings relies on browser vendors adding these warnings for the relevant features.
{{InheritanceDiagram}}
## Constructor
An instance of `InterventionReportBody` is returned as the value of {{domxref("Report.body")}} when {{domxref("Report.Type")}} is `intervention`. The interface has no constructor.
## Instance properties
This interface also inherits properties from {{domxref("ReportBody")}}.
- {{domxref("InterventionReportBody.id")}} {{experimental_inline}} {{ReadOnlyInline}}
- : A string representing the intervention that generated the report. This can be used to group reports.
- {{domxref("InterventionReportBody.message")}} {{experimental_inline}} {{ReadOnlyInline}}
- : A string containing a human-readable description of the intervention, including information such how the intervention could be avoided. This typically matches the message a browser will display in its DevTools console when an intervention is imposed, if one is available.
- {{domxref("InterventionReportBody.sourceFile")}} {{experimental_inline}} {{ReadOnlyInline}}
- : A string containing the path to the source file where the intervention occurred, if known, or `null` otherwise.
- {{domxref("InterventionReportBody.lineNumber")}} {{experimental_inline}} {{ReadOnlyInline}}
- : A string representing the line in the source file in which the intervention occurred, if known, or `null` otherwise.
- {{domxref("InterventionReportBody.columnNumber")}} {{experimental_inline}} {{ReadOnlyInline}}
- : A string representing the column in the source file in which the intervention occurred, if known, or `null` otherwise.
## Instance methods
This interface also inherits methods from {{domxref("ReportBody")}}.
- {{domxref("InterventionReportBody.toJSON()")}} {{experimental_inline}}
- : A _serializer_ which returns a JSON representation of the `InterventionReportBody` object.
## Examples
In this example we create a new {{domxref("ReportingObserver")}} to observe intervention reports, then print details of each property of the first report to the console.
```js
const options = {
types: ["intervention"],
buffered: true,
};
const observer = new ReportingObserver((reports, observer) => {
const firstReport = reports[0];
console.log(firstReport.type); // intervention
console.log(firstReport.body.id);
console.log(firstReport.body.message);
console.log(firstReport.body.sourceFile);
console.log(firstReport.body.lineNumber);
console.log(firstReport.body.columnNumber);
}, options);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Reporting API](/en-US/docs/Web/API/Reporting_API)
- [The Reporting API](https://developer.chrome.com/docs/capabilities/web-apis/reporting-api)
| 0 |
data/mdn-content/files/en-us/web/api/interventionreportbody | data/mdn-content/files/en-us/web/api/interventionreportbody/columnnumber/index.md | ---
title: "InterventionReportBody: columnNumber property"
short-title: columnNumber
slug: Web/API/InterventionReportBody/columnNumber
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.InterventionReportBody.columnNumber
---
{{APIRef("Reporting API")}}{{SeeCompatTable}}
The **`columnNumber`** read-only property of the {{domxref("InterventionReportBody")}} interface returns the line in the source file in which the intervention occurred.
> **Note:** This property is most useful alongside {{domxref("InterventionReportBody.sourceFile")}} and {{domxref("InterventionReportBody.lineNumber")}} as it enables the location of the column in that file and line where the feature is used.
## Value
An integer, or `null` if the column is not known.
## Examples
In this example we create a new {{domxref("ReportingObserver")}} to observe intervention reports, then print the value of `columnNumber` to the console.
```js
const options = {
types: ["intervention"],
buffered: true,
};
const observer = new ReportingObserver((reports, observer) => {
const firstReport = reports[0];
console.log(firstReport.type); // intervention
console.log(firstReport.body.sourceFile); // the source file
console.log(firstReport.body.lineNumber); // the line in that file
console.log(firstReport.body.columnNumber); // the column in that file.
}, options);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/interventionreportbody | data/mdn-content/files/en-us/web/api/interventionreportbody/linenumber/index.md | ---
title: "InterventionReportBody: lineNumber property"
short-title: lineNumber
slug: Web/API/InterventionReportBody/lineNumber
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.InterventionReportBody.lineNumber
---
{{APIRef("Reporting API")}}{{SeeCompatTable}}
The **`lineNumber`** read-only property of the {{domxref("InterventionReportBody")}} interface returns the line in the source file in which the intervention occurred.
> **Note:** This property is most useful alongside {{domxref("InterventionReportBody.sourceFile")}} as it enables the location of the line in that file where the feature is used.
## Value
An integer, or `null` if the line is not known.
## Examples
In this example we create a new {{domxref("ReportingObserver")}} to observe intervention reports, then print the value of `lineNumber` to the console.
```js
const options = {
types: ["intervention"],
buffered: true,
};
const observer = new ReportingObserver((reports, observer) => {
const firstReport = reports[0];
console.log(firstReport.type); // intervention
console.log(firstReport.body.sourceFile); // the source file
console.log(firstReport.body.lineNumber); // the line in that file
}, options);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.