Appearance
V3 Reference
FreshRELAY Browser SDK v2 vs v3
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
The SignalWire Client-side SDKs transform your browser into a real-time media engine, enabling developers to directly make audio and video calls to phone numbers, SIP endpoints, and other browsers. With a few lines of code, you can even set up a full-fledged video conferencing system. Using the client-side SDKs you can add immersive, scalable communication, from video conferences and softphones to click-to-call and mobile gaming, all available right in your own web pages and applications.
Depending on your use case, you can choose among two different SDK versions:
- RELAY Browser SDK v3
- RELAY Browser SDK v2
Both SDKs are JavaScript libraries that run entirely on the browser.
To help get you started, in the following we will introduce two broad and common use cases: for each of them, we suggest which of the two SDKs is the most indicated to the job. Keep into consideration that, in the near future, all functionality of RELAY Browser SDK v2 will be integrated into RELAY Browser SDK v3, which will become the reference SDK.
I am building an audio/video conferencing application
If what you are building is closely related to an audio/video conferencing application, which for example should allow the existence of multiple distinct rooms for joining by multiple people, then the RELAY Browser SDK v3 is likely to be the right tool for the job. This doesn’t sound like your use case? Then skip below.
With the RELAY Browser SDK v3, you will be able to build web pages that can stream your voice and video to other users connected to the same system. You can let your users join or leave virtual rooms with an extremely simple API. In other words, you can use the RELAY Browser SDK v3 to build your own personalized video conference experience.
Moreover, you have full granular control over the permissions within your system. You can enable some of your users to only join conference calls, while others could list ongoing calls and jump in to assist from a support Dashboard. Permissions are handled jointly with the authentication system, which uses JWTs, allowing an easy and secure control of your users’ capabilities.
At the moment, the RELAY Browser SDK v3 does not allow dialing PSTN numbers or SIP endpoints. This will become supported in the near future. For now, it means that all participants should access from a web browser. If you need to dial different endpoints, then perhaps the RELAY Browser SDK v2 suits you better. Note, however, that with the RELAY Browser SDK v2 you will have no room support.
Installing the RELAY Browser SDK v3
Starting to use the RELAY Browser SDK v3 is as easy as loading a script from a CDN. In fact, that’s exactly how you do it:
<script src="https://cdn.signalwire.com/@signalwire/js"></script>Then, you can use the global SignalWire variable in your application. If you prefer, the JavaScript SDK v3 is also available as a NPM package:
$ npm i @signalwire/jsFor getting started with the RELAY Browser SDK v3, take a look at our API reference.
I am building a one-to-one communication app that should dial other browsers or phones
If what you are building is an application that should allow your users, from their browser, to initiate an audio or video call towards other browsers, phone numbers, or SIP endpoints, then the RELAY Browser SDK v2 (Relay SDK) is the right choice for you.
By exploiting SignalWire’s powerful and flexible Relay API, the RELAY Browser SDK v2 gives you access to reliable low-latency communication over a broad set of endpoints in a seamless way, both for your users and for the developers.
As an example, with the RELAY Browser SDK v2 it is extremely easy to build a web-based call center application from which the operator can both dial PSTN phone numbers, and perform internal video calls. All with the same API.
At the moment, the RELAY Browser SDK v2 does not support the creation and management of virtual rooms. If you need a multi-room experience, the RELAY Browser SDK v3 might be more indicated for you. Note, however, that as of today the RELAY Browser SDK v3 only supports web browser endpoints, so you won’t be able to dial PSTN numbers or SIP endpoints while using the RELAY Browser SDK v3. However, these will be supported soon.
Installing the RELAY Browser SDK v2
As is the case for the RELAY Browser SDK v3, also the RELAY Browser SDK v2 can be loaded as a script from a CDN. In fact, it can be imported like this:
<script src="https://cdn.signalwire.com/@signalwire/js@1"></script>Then, you can use the global Relay variable in your application. If you prefer, the RELAY Browser SDK v2 is also available as an NPM package:
$ npm i @signalwire/js@^1For getting started with the RELAY Browser SDK v2, take a look at our documentation and API reference.
Still unsure?
Here are several use-cases, classified according to the SDK that is most indicated for them.
| RELAY Browser SDK v3 | RELAY Browser SDK v2 |
|---|---|
| Remote learning | Technical support |
| Remote work | Call center |
| Remote conferencing | Patient consultation |
PubSub
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
Classes
- Client
- PubSubMessage
PubSub.Client
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
You can use the Client object to build a messaging system into the browser.
Example usage:
import { PubSub } from "@signalwire/js";
const pubSubClient = new PubSub.Client({
token: "<your chat token>", // get this from the REST APIs
});
await pubSubClient.subscribe(["mychannel1", "mychannel2"]);
pubSubClient.on("message", (message) => {
// prettier-ignore
console.log("Received", message.content,
"on", message.channel,
"at", message.publishedAt);
});
await pubSubClient.publish({
channel: "mychannel1",
content: "hello world",
});Constructor
Creates a new PubSub client.
import { PubSub } from "@signalwire/js";
const pubSubClient = new PubSub.Client({
token: "<your chat token>"
});Parameters
token
stringRequired
SignalWire Chat token that can be obtained from the REST APIs.
Methods
disconnect\ \ Disconnect the client getAllowedChannels\ \ Get channels allowed by the token publish\ \ Publish a message to a channel subscribe\ \ Subscribe to channels unsubscribe\ \ Unsubscribe from channels updateToken\ \ Replace the client token on\ \ Subscribe to an event once\ \ Subscribe to an event once off\ \ Unsubscribe from an event removeAllListeners\ \ Remove all event listeners
Events
Events\ \ Events emitted by the PubSub.Client class.
disconnect
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
disconnect
- disconnect():
void
Disconnects this client. The client will stop receiving events and you will need to create a new instance if you want to use it again.
Returns
void
Example
client.disconnect();Events
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
The PubSub.Client object emits the events listed below. You can work with these events using the following methods:
on\ \ Subscribe to an event once\ \ Subscribe to an event once off\ \ Unsubscribe from an event removeAllListeners\ \ Remove all event listeners
Events
message
- message(
message)
A new message has been received.
Properties
message
PubSubMessage<PubSubMessageContract toc={true}>Required
The received message. See PubSubMessage for more details.
session.expiring
- session.expiring()
The session is going to expire. Use the updateToken method to refresh your token.
getAllowedChannels
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getAllowedChannels
- getAllowedChannels():
Promise<Object>
Returns the channels that the current token allows you to subscribe to.
Returns
Promise<Object>
An object whose keys are the channel names, and whose values are the permissions. For example:
{
"my-channel-1": { "read": true, "write": false },
"my-channel-2": { "read": true, "write": true },
}Example
const pubSubClient = new PubSub.Client({
token: "<your chat token>",
});
const channels = await pubSubClient.getAllowedChannels();
console.log(channels);off
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
off
- off(
event,fn?)
Remove an event handler.
Parameters
| Name | Type | Description |
|---|---|---|
event | string | Name of the event. See the list of events. |
fn? | Function | An event handler which had been previously attached. |
on
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
on
- on(
event,fn)
Attaches an event handler to the specified event.
Parameters
| Name | Type | Description |
|---|---|---|
event | string | Name of the event. See the list of events. |
fn | Function | An event handler. |
Example
In the below example, we are listening for the call.state event and logging the current call state to the console. This means this will be triggered every time the call state changes.
call.on("call.state", (call) => {
console.log("call state changed:", call.state);
});once
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
once
- once(
event,fn)
Attaches an event handler to the specified event. The handler will fire only once.
Parameters
| Name | Type | Description |
|---|---|---|
event | string | Name of the event. See the list of events. |
fn | Function | An event handler. |
publish
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
publish
- publish(
params):Promise<void>
Publish a message into the specified channel.
Parameters
params
objectRequired
Configuration object for publishing a message
params.channel
stringRequired
Channel in which to send the message.
params.content
anyRequired
The message to send. This can be any JSON-serializable object.
params.meta
Record<any, any toc={true}>
Metadata associated with the message. There are no requirements on the content of metadata.
Returns
Promise<void>
Examples
Publishing a message as a string:
await pubSub.publish({
channel: "my-channel",
content: "Hello, world."
});Publishing a message as an object:
await pubSub.publish({
channel: "my-channel",
content: {
field_one: "value_one",
field_two: "value_two"
},
});removeAllListeners
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
removeAllListeners
- removeAllListeners(
event?)
Detaches all event listeners for the specified event.
Parameters
| Name | Type | Description |
|---|---|---|
event? | string | Name of the event (leave this undefined to detach listeners for all events). See the list of events. |
subscribe
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
subscribe
- subscribe(
channels):Promise<void>
List of channels for which you want to receive messages. You can only subscribe to those channels for which your token has read permission.
Note that the subscribe function is idempotent, and calling it again with a different set of channels will not unsubscribe you from the old ones. To unsubscribe, use unsubscribe.
Parameters
channels
string | string[]Required
The channels to subscribe to, either in the form of a string (for one channel) or an array of strings.
Returns
Promise<void>
Example
const pubSub = new PubSub.Client({
token: "<your chat token>"
});
pubSub.on("message", (m) => console.log(m));
await pubSub.subscribe("my-channel");
await pubSub.subscribe(["chan-2", "chan-3"]);unsubscribe
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
unsubscribe
- unsubscribe(
channels):Promise<void>
List of channels from which you want to unsubscribe.
Parameters
channels
string | string[]Required
The channels to unsubscribe from, either in the form of a string (for one channel) or an array of strings.
Returns
Promise<void>
Example
await pubSub.unsubscribe("my-channel");
await pubSub.unsubscribe(["chan-2", "chan-3"]);updateToken
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
updateToken
- updateToken(
token):Promise<void>
Replaces the token used by the client with a new one. You can use this method to replace the token when, for example, it is expiring, in order to keep the session alive.
The new token can contain different channels from the previous one. In that case, you will need to subscribe to the new channels if you want to receive messages for those. Channels that were in the previous token but are not in the new one will get unsubscribed automatically.
Parameters
token
stringRequired
The new token.
Returns
Promise<void>
Example
const pubSubClient = new PubSub.Client({
token: '<your chat token>'
})
pubSubClient.on('session.expiring', async () => {
const newToken = await fetchNewToken(..)
await pubSubClient.updateToken(newToken)
})PubSubMessage
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
Represents a message in a PubSub context.
Properties
channel
The channel in which this message was sent.
Syntax:PubSubMessage.channel()
Returns:string
content
The content of this message.
Syntax:PubSubMessage.content()
Returns:string
id
The id of this message.
Syntax:PubSubMessage.id()
Returns:string
meta
Any metadata associated to this message.
Syntax:PubSubMessage.meta()
Returns:any
publishedAt
The date and time at which this message was published.
Syntax:PubSubMessage.publishedAt()
Returns:Date
SignalWire Client
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
The SignalWire client enables the SignalWire’s vision for Programmable Unified Communications. It allows a new paradigm in communications, designed to streamline usage and development across all communication types.
The following section details the mechanisms available in the SignalWire browser SDK @signalwire/js to take advantage of the unified communication architecture.
Installation
The SignalWire client is available in the SignalWire Browser SDK @signalwire/js versions 3.27.0 and later.
If your project uses a package manager, the Browser SDK can be installed like so:
npm2yarn
npm install @signalwire/js@3It is also available through our CDN and can be included directly into the <head> section of your webpage.
<script src="https://cdn.signalwire.com/@signalwire/js"></script>Once installed, you can take advantage of the new capabilities that the SignalWire client enables by instantiating a SignalWire Client, like so:
<script type="text/javascript" src="https://cdn.signalwire.com/@signalwire/js"></script>
<script>
async function main() {
const client = await SignalWire.SignalWire({
token: "<TOKEN>",
});
}
</script>The access token is received after the subscriber completes the OAuth2 flow and successfully logs in. Learn more at the Authentication section further below.
Concepts
Resources
Resources are the primary entities for communication within SignalWire. Resources include: Subscribers SWML Scripts, SignalWire AI Agents, Video-Rooms, SIP Endpoints, etc.
Subscribers
Subscribers represent the end-users within SignalWire. They are the endpoints of communication, capable of receiving or initiating calls, messages, and other forms of interaction.
SignalWire allows subscribers to switch from one type of communication to another. For example, switching from a phone call into a video-room to a web-based video call.
You can create Subscribers and Resources in the Resource section of your SignalWire Dashboard, or with a HTTP POST request:
curl --location --request POST 'https://spacename.signalwire.com/api/fabric/subscribers' \
--user "project_id:api key" \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "[the subscriber email]",
"password": "[the subscriber password]"
}'Addresses
Each resource and subscriber is uniquely identified by an addresses which can be called, sent messages to, or interacted with in some other way.
The address is composed of two parts: “/context/name”
- Context: A identifier that indicates in which context the resource is located.
- Name: The name is the unique identifier for the resource.
For example, the address for a Subscribers resource named Alice in the public context would be /public/Alice.
Authentication
As explained in the Subscribers section above, Subscribers represent the end-users within SignalWire, thus usually actions are performed on behalf of the subscriber.
So, when using the SignalWire Client, you will need a Subscriber’s token to authenticate your requests. Usually, that token is obtained when the subscriber logs in using the OAuth2 flow described further below. But your server applications can perform actions on behalf of the subscriber by using getting a token using the REST API.
REST API Token Authentication
You can obtain authentication tokens directly through the REST API. The following endpoints are available for token generation:
Create a Guest Token
Generate a limited-access token for guest access to specific Fabric addresses.
POST
/api/fabric/guests/tokens
cURL
curl -X POST https://{your_space_name}.signalwire.com/api/fabric/guests/tokens \
-H "Content-Type: application/json" \
-u "<project_id>:<api_token>" \
-d '{
"allowed_addresses": [\
"string"\
]
}'Try it
Create a Subscriber Invite Token
Generate a token to access resources associated with a specific subscriber on behalf of the subscriber.
POST
/api/fabric/subscriber/invites
cURL
curl -X POST https://{your_space_name}.signalwire.com/api/fabric/subscriber/invites \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{
"address_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
}'Try it
Create a new Subscriber and a Token
Create a new subscriber and get their token in a single request.
POST
/api/fabric/subscribers/tokens
cURL
curl -X POST https://{your_space_name}.signalwire.com/api/fabric/subscribers/tokens \
-H "Content-Type: application/json" \
-u "<project_id>:<api_token>" \
-d '{
"reference": "john.doe@example.com"
}'Try it
For browser-based applications, we recommend using the OAuth2 flow to authenticate subscribers and obtain tokens. See Authenticate subscribers using OAuth2 below for details.
Using the Token
The endpoints return a JSON object containing a token property. Use this token to initialize the SignalWire Client:
import { SignalWire } from "@signalwire/js";
const client = await SignalWire({
token: "eyJhbGciOiJIUzI1NiIs..."
});Authenticate subscribers using OAuth2
When you create a Subscriber, you assign them a username (email) and a password. These credentials can be used authenticate the subscriber using the standard OAuth2 flow with PKCE. For OAuth2, you can use tools like odic-client-ts or react-native-app-auth.
Currently, the only way to get a client ID for the OAuth2 flow is through the SignalWire Support team.
oidc-client-ts
react-native-app-auth
import { UserManager, WebStorageStateStore } from "oidc-client-ts";
const config = {
authority: "x", // dummy authority
metadata: {
issuer: "https://id.fabric.signalwire.com/",
authorization_endpoint: "https://id.fabric.signalwire.com/login/oauth/authorize",
token_endpoint: "https://id.fabric.signalwire.com/oauth/token",
},
client_id: "<Your_Fabric_Client_id>",
redirect_uri: "https://redirect_uri",
response_type: "code",
userStore: new WebStorageStateStore({ store: window.localStorage }),
};
const userManager = new UserManager(config);
await userManager.signinRedirect();A complete example is presented below. Assuming that this page is npx served at the address http://localhost:3000, this script takes the subscriber through the OAuth2 login flow, and uses the access token received to fetch the subscriber’s registration details from SignalWire.
index.html
<html>
<head>
<style>
.loading > button { display: none }
.loading::after { content: "Loading..." }
</style>
</head>
<body>
<div id="container" class="loading">
<button onclick="userManager.signinRedirect()">Log In</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/oidc-client-ts@3.0.1/dist/browser/oidc-client-ts.min.js"></script>
<script src="https://cdn.signalwire.com/@signalwire/js"></script>
<script>
const container = document.getElementById("container");
const config = {
authority: "x", // dummy authority
metadata: {
issuer: "https://id.fabric.signalwire.com/",
authorization_endpoint: "https://id.fabric.signalwire.com/login/oauth/authorize",
token_endpoint: "https://id.fabric.signalwire.com/oauth/token",
},
client_id: "<Your_Fabric_Client_id>",
redirect_uri: "http://localhost:3000", // assuming this page is being served at port 3000 of localhost
response_type: "code",
userStore: new oidc.WebStorageStateStore({ store: window.localStorage }),
};
const userManager = new oidc.UserManager(config);
async function checkForRedirect() {
try {
const user = await userManager.signinRedirectCallback();
if (user) {
// the oauth flow completed successfully, we can now use subscriber features using the access token.
await getSubscriberInfo(user.access_token);
}
} catch (e) {
// signinRedirectCallback failed; login flow hasn't been started yet. We'll show the Login button.
container.classList.remove("loading");
}
}
async function getSubscriberInfo(token) {
const client = await SignalWire.SignalWire({ token });
const subInfo = await client.getSubscriberInfo();
container.classList.remove("loading");
container.innerText = `Hello, ${subInfo.first_name}`;
}
// We want to check if the user was redirected here from the subscriber login flow,
// or if the came here directly from the browser. If the user came directly from the
// browser, we show a Login button. If they were redirected here, we allow oidc-client-ts
// to finish the flow and get the access token.
checkForRedirect();
</script>
</body>
</html>The SignalWire Client
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
The SignalWire Client provides access to SignalWire’s services on the browser. It provides methods to handle incoming calls, dial to addresses, and register devices for notifications.
Instantiation
The SignalWire client is instantiated using the SignalWire function.
If you’re including the @signalwire/js dependency as a script in HTML, the SignalWire function is a property of the SignalWire global variable that the script sets:
<script type="text/javascript" src="https://cdn.signalwire.com/@signalwire/js"></script>
<script>
async function main() {
const client = await SignalWire.SignalWire({
token: "<TOKEN>",
});
}
</script>If you installed @signalwire/js from npm:
import { SignalWire } from "@signalwire/js";
async function main() {
const client = await SignalWire({
token: "<TOKEN>",
});
}For React or React Native projects, use the community library:
import { useSignalWire } from "@signalwire-community/react";
export default function App() {
const client = useSignalWire({
token: "<TOKEN>",
});
}Parameters
token
stringRequired
The access token for the subscriber.
rootElement
HTMLElement
The HTML container element where the SDK will display the video stream.
incomingCallHandlers
IncomingCallHandlers
Callback functions for when a call is received. See IncomingCallHandlers.
userVariables
Record<string, any toc={true}>
Arbitrary variables that are transparent to FreeSWITCH.
You can manage the DOM yourself by not specifying a rootElement here and using the buildVideoElement function instead.
Example
Vanilla JS
React (community)
<html>
<body>
<script type="text/javascript" src="https://cdn.signalwire.com/@signalwire/js"></script>
<script>
async function main() {
const client = await SignalWire.SignalWire({
token: "<TOKEN>",
});
const conversations = await client.conversation.getConversations();
console.log(conversations);
const addresses = await client.address.getAddresses();
console.log(addresses);
}
main();
</script>
</body>
</html>Properties
httpHost
string
Returns the URL of the host that the client will use to make HTTP requests (like querying the list of addresses or conversations). Read-only.
console.log(client.httpHost());
// fabric.signalwire.comMethods
dial\ \ Dial to an address online\ \ Go online to receive call invites offline\ \ Go offline to stop receiving call invites getSubscriberInfo\ \ Get info about the current subscriber connect\ \ Connect the WebSocket client disconnect\ \ Disconnect the WebSocket client updateToken\ \ Update the auth token
Namespaces
Certain methods and properties are organized into namespaces for clarity. They can be accessed as follows:
client.address.getAddresses();
client.chat.getMessages();
client.conversation.getConversations();Address\ \ Methods for working with addresses Chat\ \ Methods for chat functionality Conversation\ \ Methods for conversations
Type aliases
IncomingCallHandlers
Use this object to assign callback functions which get invoked when a call is received.
| Name | Type | Required? | Description |
|---|---|---|---|
all | (IncomingCallNotification) => void | Optional | Since push support has been removed, identical to websocket |
websocket | (IncomingCallNotification) => void | Optional | Callback for calls received via websocket (overrides all) |
IncomingCallNotification
The object passed into the IncomingCallHandlers callback with the call description and controls.
| Name | Type | Description |
|---|---|---|
invite | object | - |
invite.details | IncomingInvite | The details of the invite. |
invite.accept | (CallOptions) => Promise<CallFabricRoomSession> | Invoke this function to accept the incoming call |
invite.reject | () => Promise<void> | Invoke this function to reject the incoming call |
IncomingInvite
| Name | Type | Description |
|---|---|---|
source | "websocket" | |
callID | string | Unique ID of the incoming call |
sdp | string | Deprecated |
caller_id_name | string | Name of the caller |
caller_id_number | string | ID or number of the caller |
callee_id_name | string | Name of the callee |
callee_id_number | string | ID or number of the callee |
display_direction | string | Direction of the call |
nodeId | string | The node from where the call was received |
CallOptions
| Name | Type | Required? | Description |
|---|---|---|---|
rootElement | HTMLElement | Optional | The HTML container element where the SDK will display the video stream. |
audio | `boolean | MediaTrackConstraints` | Optional |
video | `boolean | MediaTrackConstraints` | Optional |
disableUdpIceServers | boolean | Optional | Disables the ICE UDP transport policy. |
userVariables | Record<string, any> | Optional | Arbitrary variables that are transparent to FreeSWITCH. |
MediaStreamConstraints
| Name | Type | Required? | Description |
|---|---|---|---|
audio | `boolean | MediaTrackConstraints` | Optional |
video | `boolean | MediaTrackConstraints` | Optional |
peerIdentity | string | Optional | Peer identity. |
preferCurrentTab | boolean | Optional | Whether to prefer current tab for the call. |
CallFabricRoomSession
Extends RoomSession.
| Name | Type | Description |
|---|---|---|
start | () => void | Starts the call. |
answer | `boolean | MediaTrackConstraints` |
hangup | (id?) => void | Ends the ongoing call by default. If the id of an RTCPeer is passed, hangs up that RTCPeer. |
Address Namespace
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
The Address namespace includes methods that give you access to Address objects.
The address object
The Address object represents a unique identifier for different types of entities in the system. Each address has the following properties:
| Field | Description |
|---|---|
id | A unique identifier for the address. |
name | The name of the address. |
display_name | The display name of the address. |
type | The type of the address. It can be one of the following: subscriber, room, app, call. |
cover_url | The URL of the cover image for the address. This can be null. |
preview_url | The URL of the preview image for the address. This can be null. |
channels | An object containing the audio, video, and messaging channels for the address. Each channel is represented by a URL. |
Here is an example of an Address object:
{
"id": "39e38f64-d694-4b62-ace8-a2b91359abca",
"name": "jim-carrey",
"display_name": "Jim Carrey",
"type": "subscriber",
"cover_url": "null",
"preview_url": null,
"channels": {
"audio": "/private/jim-carrey?channel=audio",
"video": "/private/jim-carrey?channel=video"
}
}Methods
getAddresses
- getAddresses(
options):Promise<{ data: Address[], hasNext, hasPrev }>
Returns a list of Addresses.
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
options | object | - | |
options.type? | string | undefined | The address type to filter for. Possible values: subscriber, room, app, call. |
options.displayName? | string | undefined | The address display name to filter for |
Returns
Promise<{ data: Address[], hasNext, hasPrev }>
Example
await client.address.getAddresses();{
"data": [\
{\
"id": "39e38f64-d694-4b62-ace8-a2b91359abca",\
"name": "jim-carrey",\
"display_name": "Jim Carrey",\
"type": "subscriber",\
"cover_url": "null",\
"preview_url": null,\
"channels": {\
"audio": "/private/jim-carrey?channel=audio",\
"video": "/private/jim-carrey?channel=video"\
}\
},\
{\
"id": "39e38f64-d694-4b62-ace8-a2b91359abca",\
"name": "john-travolta",\
"display_name": "John Travolta",\
"type": "subscriber",\
"cover_url": "null",\
"preview_url": null,\
"channels": {\
"audio": "/private/john-travolta?channel=audio",\
"video": "/private/john-travolta?channel=video"\
}\
}\
],
"hasNext": false,
"hasPrev": false
}getAddress
- getAddress(
options):Promise<Address>
Get the details of a particular address ID.
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
options | object | - | |
options.id | string | undefined | The ID to get address details for. |
Returns
Promise<Address>
Example
await client.address.getAddress({ id: "39e38f64-d694-4b62-ace8-a2b91359abca" });{
"id": "39e38f64-d694-4b62-ace8-a2b91359abca",
"name": "jim-carrey",
"display_name": "Jim Carrey",
"type": "subscriber",
"cover_url": "null",
"preview_url": null,
"channels": {
"audio": "/private/jim-carrey?channel=audio",
"video": "/private/jim-carrey?channel=video"
}
}connect
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
connect
- connect():
void
Connects to the WebSocket client. SignalWire manages the WebSocket connection automatically in most cases, so you’ll only need to use connect in the rare edge cases when you need to manually manage the connection.
Returns
void
Conversation Namespace
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
The Conversation namespace includes methods that give you access to Conversation and ConversationMessage objects.
The Conversation Object
Conversation objects represent interaction pairs between Subscribers and Addresses. Each Conversation object has the following properties:
| Field | Description |
|---|---|
id | A unique identifier for the conversation. |
name | The name of the conversation. |
metadata | Additional metadata associated with the conversation. |
created_at | The UNIX timestamp when the conversation was created. |
last_message_at | The UNIX timestamp of the last message in the conversation. |
Here is an example of a Conversation object:
{
"id": "9dbe9e94-c797-461e-b5a3-af6d095deaf4",
"name": "conversation-office",
"metadata": {},
"created_at": 1708192187729,
"last_message_at": 1708192187823
}The ConversationMessage object
ConversationMessage objects represent the specific interactions that have taken place in the Conversation:
id: A unique identifier for the conversation message.conversation_id: A unique identifier of the parent conversation.user_id: A unique identifier for the subscriber.ts: The timestamp, in Unix Epoch, when the message was created.details: Additional metadata associated with the conversation.type: The type of the conversation message.subtype: The subtype of the conversation message.kind: The kind of the conversation message.
Here is an example of a ConversationMessage object:
{
"id": "3c114417-5cc0-4d03-a30f-c90659028d73",
"conversation_id": "9dbe9e94-c797-461e-b5a3-af6d095deaf4",
"user_id": "cecbe021-ff86-4ac6-bdf3-399ca477ad6f",
"ts": 1708192187.6779745,
"details": {},
"type": "message",
"subtype": "log",
"kind": "call_started"
}Methods
getConversations
- getConversations():
Promise<{ data: Conversation[], hasNext, hasPrev }>-
Returns a list of Conversation objects.
Returns
Promise<{ data: Conversation[], hasNext, hasPrev }>
Example
await client.conversation.getConversations();{
"data": [\
{\
"id": "9dbe9e94-c797-461e-b5a3-af6d095deaf4",\
"name": "conversation-office",\
"metadata": {},\
"created_at": 1708192187729,\
"last_message_at": 1708192187823\
}\
],
"hasNext": false,
"hasPrev": false
}getConversationMessages
- getConversationMessages(
options):Promise<{ data: ConversationMessage[], hasNext, hasPrev }>
Returns a list of ConversationMessage objects inside a Conversation with an Address ID.
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
options | object | - | |
options.addressId | string | undefined | Get Conversation Messages for between the Subscriber and this Address ID. |
options.limit? | number | undefined | The maximum number of messages to retrieve. |
options.since? | number | undefined | The Unix timestamp in seconds to retrieve messages since. |
options.until? | number | undefined | The Unix timestamp in seconds to retrieve messages until. |
Returns
Promise<{ data: ConversationMessage[], hasNext, hasPrev }>
Example
await client.conversation.getConversationMessages({
addressId: "9dbe9e94-c797-461e-b5a3-af6d095deaf4",
});{
"data": [\
{\
"id": "3c114417-5cc0-4d03-a30f-c90659028d73",\
"conversation_id": "9dbe9e94-c797-461e-b5a3-af6d095deaf4",\
"user_id": "cecbe021-ff86-4ac6-bdf3-399ca477ad6f",\
"ts": 1708192187.6779745,\
"details": {},\
"type": "message",\
"subtype": "log",\
"kind": "call_started"\
}\
],
"hasNext": false,
"hasPrev": false
}getMessages
- getMessages(
options):Promise<{ data: ConversationMessage[], hasNext, hasPrev }>
Returns a list of ConversationMessage objects without filtering by Address ID.
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
options | object | - | |
options.limit? | number | undefined | The maximum number of messages to retrieve. |
options.since? | number | undefined | The Unix timestamp in seconds to retrieve messages since. |
options.until? | number | undefined | The Unix timestamp in seconds to retrieve messages until. |
Returns
Promise<{ data: ConversationMessage[], hasNext, hasPrev }>
Example
await client.conversation.getMessages();{
"data": [\
{\
"id": "3c114417-5cc0-4d03-a30f-c90659028d73",\
"conversation_id": "9dbe9e94-c797-461e-b5a3-af6d095deaf4",\
"user_id": "cecbe021-ff86-4ac6-bdf3-399ca477ad6f",\
"ts": 1708192187.6779745,\
"details": {},\
"type": "message",\
"subtype": "log",\
"kind": "call_started"\
}\
],
"hasNext": false,
"hasPrev": false
}subscribe
- subscribe():
Promise<void>
Subscribe to receive new ConversationMessage objects as they happen.
Returns
Promise<void>
Example
client.conversation.subscribe((conversationMessage) => {
console.log("New message received!", conversationMessage);
// Add conversationMessage to the UI
});{
"id": "916ea1c0-3381-42a3-8ca1-1095f13b4af0",
"type": "message",
"subtype": "log",
"kind": "call_started",
"hidden": "false",
"address_id": "9dbe9e94-c797-461e-b5a3-af6d095deaf4",
"conversation_id": "9dbe9e94-c797-461e-b5a3-af6d095deaf4",
"user_id": "cecbe021-ff86-4ac6-bdf3-399ca477ad6f",
"ts": 1708621363.211084,
"metadata": {},
"details": {},
"text": null,
"conversation_name": "conversation-office",
"user_name": "Jim Carrey"
}sendMessage
- sendMessage(
options):Promise<Conversation>
Sends a Chat Message to the Conversation. This is the same function as chat.sendMessage.
Parameters
| Name | Type | Description |
|---|---|---|
options | object | |
options.addressId | string | The id of the address to send the message to. |
options.text | string | The Message text content. |
options.metadata? | object | Metadata to go along with the Message. |
options.details? | object | Extra Message event details. Can be used to construct custom UIs, for example. |
Example
await conversation.sendMessage({
text: "Hello from SignalWire!",
});join
- join(
options):Promise<JoinConversationResponse>
Joins a conversation given an address, without having to send a message. Does nothing if you were already joined to the conversation. This is the same function as chat.join.
You automatically join a conversation when you send the first message to an address. The join method allows you to join a conversation without sending a message.
Parameters
| Name | Type | Description |
|---|---|---|
options | object | |
options.addressId | string | The id of the address to join the conversation of. |
Example
await conversation.join({
addressId: "9dbe9e94-c797-461e-b5a3-af6d095deaf4",
});dial
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
dial
- dial(
params):Promise<Call>
Dials to the address specified in the to parameter, and returns a Call object if successful.
Parameters
params
objectRequired
Dial parameters
params.to
stringRequired
The address of the subscriber to dial (like /private/user1).
params.rootElement
HTMLElement
The HTML container element to inject the Call into.
params.nodeId
string
Optional node ID.
You can manage the DOM yourself by not specifying a rootElement here and using the buildVideoElement function instead.
Also accepts all CallOptions parameters. Parameters passed when dialing will override any matching parameters passed during instantiation.
Returns
Promise<Call>
A Call object that describes the ongoing call, and provides handles for controlling it.
disconnect
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
disconnect
- disconnect():
void
Disconnects from the WebSocket client. SignalWire manages the WebSocket connection automatically in most cases.
Returns
void
getSubscriberInfo
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getSubscriberInfo
- getSubscriberInfo():
Promise<Object>
Get information about the subscriber that is currently logged in.
Returns
Promise<Object>
Example
const client = SignalWire({ token: /* the access token of the currently logged in user */ })
console.log(await client.getSubscriberInfo()){
"id": "0bc4b6fe-f388-4a6b-bee3-56096e9420ac",
"email": "john@example.com",
"first_name": "John",
"last_name": "Doe",
"display_name": "John Doe",
"job_title": "Engineer",
"time_zone": "PST",
"country": "US",
"region": "East",
"company_name": "Example Inc",
"app_settings": {
"display_name": "Cool Application",
"scopes": ["read", "write"]
}
}offline
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
offline
- offline():
void
Set the client to be offline so it doesn’t receive call invites via WebRTC.
Returns
void
online
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
online
- online(
options):Promise<Call>
Set the client to be online so it can receive call invites via WebRTC. The call invites can be accepted or rejected as per user input.
Parameters
options
objectRequired
Options object
options.incomingCallHandlers
IncomingCallHandlers
Callback functions for when a call is received. See IncomingCallHandlers.
Example
// Receive calls using websocket notifications
client.online({
incomingCallHandlers: {
all: __incomingCallHandler,
},
});
// Function to handle the incoming call notification and stores the invite
window.__incomingCallHandler = (notification) => {
if (
!window.__invite ||
window.__invite.details.callID !== notification.invite.details.callID
) {
// Store call invite
window.__invite = notification.invite;
}
// Trigger UI update here to convey the ringing state
};
// Function to answer the call
window.answer = async () => {
// Accept the call invite
const call = await window.__invite.accept({
rootElement: document.getElementById("rootElement"),
});
// Trigger UI update here to convey the connected state
};
// Function to reject the call
window.reject = async () => {
await window.__invite.reject();
// Trigger UI update here to convey the ready state
};updateToken
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
updateToken
- updateToken(
token:string):Promise<void>
Update the auth token being used by the client. Use this when the old token is about to expire and you have refreshed it through OAuth2.
Parameters
token
stringRequired
The new token that the client should start to use.
Returns
Promise<void>
Returns empty object when successful. Throws an error with the server’s error message when unsuccessful.
Example
import { SignalWire } from "@signalwire/js";
async function main() {
const client = await SignalWire({
token: "<TOKEN>",
onRefreshToken: () => {
let newToken = refreshToken(); // this function should refresh token as per OAuth2 protocol
client.updateToken(newToken);
},
});
}Notifications
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
If you’ve initialized the SignalWire Client with a subscriber token, you can opt into receiving notifications whenever that subscriber address is called using WebSockets.
The WebSocket notifications are delivered over the WebSocket connection while your application is active, and you have called the online() method to opt into receiving them.
To receive incoming call notifications over WebSocket, call client.online() with an incomingCallHandlers object:
client.online({
incomingCallHandlers: {
websocket: (callInvite) => {
const callerName = callInvite.invite.details?.caller_id_name;
const callerNumber = callInvite.invite.details?.caller_id_number;
// to accept:
const roomSession = await callInvite.invite.accept(params);
// to reject:
callInvite.invite.reject();
},
},
});When an incoming call arrives, the websocket handler receives a callInvite object containing:
callInvite.invite.details- call and caller informationIncomingInvitecallInvite.invite.accept()- accepts the call and returns aCallSessioncallInvite.invite.reject()- rejects the call
Utility functions
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
buildVideoElement
- buildVideoElement(
options):Promise<BuildVideoElementReturnType>
A function that creates and optionally injects a video DOM element for a given Call or Room object.
If you have passed a rootElement when instantiating the SignalWire client, or when dial ing a call, the SDK will manage the DOM automatically; injecting the resulting video stream into the rootElement that you specified.
But for more fine grained control, or if you’re using a library like React, you can choose to manually manage DOM using this function. Be sure to not specify a rootElement at instantiation or during dialing.
Parameters
| Name | Type | Required? | Description |
|---|---|---|---|
options | object | Required | |
options.room | CallFabricRoomSession | Required | The Call Fabric Room Session to build the video element for |
options.rootElement | HTMLElement | Optional | The HTML container element which will contain the video stream. If rootElement is not passed, the resulting DOM element will be returned, and can be injected into any container element manually. |
options.applyLocalVideoOverlay | boolean | Optional | Whether to apply local video overlays on the remote stream |
Response
| Name | Type | Description |
|---|---|---|
response | object | - |
response.element | HTMLElement | The container for the stream. If rootElement was not passed, this is a newly created container. Otherwise, it is the same as the rootElement which was passed in. |
response.unsubscribe | ()=>void | Call this function to turn off all event handling for the stream before disposing of the container element. |
Example
After the SignalWire Client has been instantiated, you can dial a video call and inject it into the DOM as follows:
const call = await client.dial({
/* ... */
});
await call.start();
const { element, unsubscribe } = await buildVideoElement({
room: call,
});
const container = document.getElementById("container");
container.appendChild(element);Alternatively, you can pass in the rootElement parameter and let the function automatically manage DOM:
const { element, unsubscribe } = await buildVideoElement({
room: call,
rootElement: document.getElementById("container"),
});WebRTC
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
The WebRTC namespace includes functions that give you access to the input and output media devices available on the user’s machine. For example, you can use these functions to request permission and get access to the media stream from a webcam, from a microphone, or from a screen sharing.
Functions
checkCameraPermissions\ \ Check camera permission status checkMicrophonePermissions\ \ Check microphone permission status checkPermissions\ \ Check permission status for any resource checkSpeakerPermissions\ \ Check speaker permission status createCameraDeviceWatcher\ \ Watch for camera device changes createDeviceWatcher\ \ Watch for device changes createMicrophoneAnalyzer\ \ Track microphone input volume createMicrophoneDeviceWatcher\ \ Watch for microphone device changes createSpeakerDeviceWatcher\ \ Watch for speaker device changes enumerateDevices\ \ List available media devices getCameraDevices\ \ Get accessible camera devices getDevices\ \ Get available media devices getDisplayMedia\ \ Capture a screen or window getMicrophoneDevices\ \ Get accessible microphone devices getSpeakerDevices\ \ Get accessible speaker devices getSupportedConstraints\ \ Get browser-supported media constraints getUserMedia\ \ Request access to camera or microphone requestPermissions\ \ Prompt user for device permissions setMediaElementSinkId\ \ Set audio output device for an element stopStream\ \ Stop all tracks in a stream stopTrack\ \ Stop a single media track supportsGetDisplayMedia\ \ Check getDisplayMedia support supportsGetUserMedia\ \ Check getUserMedia support supportsMediaDevices\ \ Check media devices API support supportsMediaOutput\ \ Check media output selection support getCameraDevicesWithPermissions\ \ Get camera devices (deprecated) getDevicesWithPermissions\ \ Get devices with permissions prompt (deprecated) getMicrophoneDevicesWithPermissions\ \ Get microphone devices (deprecated) getSpeakerDevicesWithPermissions\ \ Get speaker devices (deprecated)
checkCameraPermissions
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
checkCameraPermissions
ConstcheckCameraPermissions():Promise<null | boolean>
Asynchronously returns whether we have permissions to access the camera.
Returns
Promise<null | boolean>
Example
await SignalWire.WebRTC.checkCameraPermissions();
// truecheckMicrophonePermissions
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
checkMicrophonePermissions
ConstcheckMicrophonePermissions():Promise<null | boolean>
Asynchronously returns whether we have permissions to access the microphone.
Returns
Promise<null | boolean>
Example
await SignalWire.WebRTC.checkMicrophonePermissions();
// truecheckPermissions
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
checkPermissions
ConstcheckPermissions(name?):Promise<null | boolean>
Asynchronously returns whether we have permissions to access the specified resource. Some common parameter values for name are "camera", "microphone", and "speaker". In those cases, prefer the dedicated functions checkCameraPermissions, checkMicrophonePermissions, and checkSpeakerPermissions.
Parameters
name
DevicePermissionName
Name of the resource.
Returns
Promise<null | boolean>
Example
await SignalWire.WebRTC.checkPermissions("camera");
// true: we have permission for using the cameracheckSpeakerPermissions
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
checkSpeakerPermissions
ConstcheckSpeakerPermissions():Promise<null | boolean>
Asynchronously returns whether we have permissions to access the speakers.
Returns
Promise<null | boolean>
Example
await SignalWire.WebRTC.checkSpeakerPermissions();
// truecreateCameraDeviceWatcher
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
createCameraDeviceWatcher
ConstcreateCameraDeviceWatcher():Promise<EventEmitter<DeviceWatcherEvents, any>>
Asynchronously returns an event emitter that notifies changes in all camera devices. This is equivalent to calling createDeviceWatcher({ targets: ['camera'] }), so refer to createDeviceWatcher for additional information about the returned event emitter.
Returns
Promise<EventEmitter<DeviceWatcherEvents, any>>
createDeviceWatcher
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
createDeviceWatcher
ConstcreateDeviceWatcher(options?):Promise<EventEmitter<DeviceWatcherEvents, any>>
Asynchronously returns an event emitter that notifies changes in the devices. The possible events are:
"added": A device has been added."removed": A device has been removed."updated": A device has been updated."changed": Any of the previous events occurred.
In all cases, your event handler gets as parameter an object e with the following keys:
e.changes: The changed devices. For"added","removed", and"updated"event handlers, you only get the object associated to the respective event (i.e., only a list of added devices, removed devices, or updated devices). For"changed"event handlers, you get all three lists.e.devices: The new list of devices.
For device-specific helpers, see createCameraDeviceWatcher, createMicrophoneDeviceWatcher, and createSpeakerDeviceWatcher.
Parameters
options
CreateDeviceWatcherOptions
If omitted, the event emitter is associated to all devices for which we have permission. Otherwise, pass an object { targets: string[] }, where targets is a list of categories. Allowed categories are "camera", "microphone", and "speaker".
Returns
Promise<EventEmitter<DeviceWatcherEvents, any>>
Examples
Creating an event listener on the "changed" event:
await SignalWire.WebRTC.getUserMedia({ audio: true, video: false });
h = await SignalWire.WebRTC.createDeviceWatcher();
h.on("changed", (c) => console.log(c));Getting notified only for audio input and output devices:
h = await SignalWire.WebRTC.createDeviceWatcher({
targets: ["microphone", "speaker"],
});
h.on("changed", (c) => console.log(c));createMicrophoneAnalyzer
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
createMicrophoneAnalyzer
ConstcreateMicrophoneAnalyzer(options):Promise<MicrophoneAnalyzer>
Initializes a microphone analyzer. You can use a MicrophoneAnalyzer to track the input audio volume.
To stop the analyzer, call the destroy() method on the returned object.
The returned object emits the following events:
volumeChanged: Instantaneous volume from 0 to 100.destroyed: The object has been destroyed. The parameter describes the reason:null(if you calleddestroy()),"error"(in case of errors), or"disconnected"(if the device was disconnected).
Parameters
options
string | MediaStream | MediaTrackConstraintsRequired
Either the id of the device to analyze, a MediaStreamConstraints object, or a MediaStream.
Returns
Promise<MicrophoneAnalyzer>
Example
const micAnalyzer = await createMicrophoneAnalyzer("device-id");
micAnalyzer.on("volumeChanged", (vol) => {
console.log("Volume: ", vol);
});
micAnalyzer.on("destroyed", (reason) => {
console.log("Microphone analyzer destroyed", reason);
});
micAnalyzer.destroy();createMicrophoneDeviceWatcher
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
createMicrophoneDeviceWatcher
ConstcreateMicrophoneDeviceWatcher():Promise<EventEmitter<DeviceWatcherEvents, any>>
Asynchronously returns an event emitter that notifies changes in all microphone devices. This is equivalent to calling createDeviceWatcher({ targets: ['microphone'] }), so refer to createDeviceWatcher for additional information about the returned event emitter.
Returns
Promise<EventEmitter<DeviceWatcherEvents, any>>
createSpeakerDeviceWatcher
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
createSpeakerDeviceWatcher
ConstcreateSpeakerDeviceWatcher():Promise<EventEmitter<DeviceWatcherEvents, any>>
Asynchronously returns an event emitter that notifies changes in all speaker devices. This is equivalent to calling createDeviceWatcher({ targets: ['speaker'] }), so refer to createDeviceWatcher for additional information about the returned event emitter.
Returns
Promise<EventEmitter<DeviceWatcherEvents, any>>
enumerateDevices
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
enumerateDevices
ConstenumerateDevices():Promise<MediaDeviceInfo[]>, See MediaDeviceInfo for more details.
Enumerates the media input and output devices available on this device.
Depending on the browser, some information (such as the label and deviceId attributes) could be hidden until permission is granted, for example by calling getUserMedia.
Returns
Promise<MediaDeviceInfo[]>
Example
await SignalWire.WebRTC.enumerateDevices();
// [\
// {\
// "deviceId": "Rug5Bk...4TMhY=",\
// "kind": "videoinput",\
// "label": "HD FaceTime Camera",\
// "groupId": "EEX/N2...AjrOs="\
// },\
// ...\
// ]getCameraDevices
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getCameraDevices
ConstgetCameraDevices():Promise<MediaDeviceInfo[]>, See MediaDeviceInfo for more details.
Returns an array of camera devices that can be accessed on this device (for which we have permissions).
Returns
Promise<MediaDeviceInfo[]>
Example
await SignalWire.WebRTC.getCameraDevices();
// [\
// {\
// "deviceId": "Rug5Bk...4TMhY=",\
// "kind": "videoinput",\
// "label": "HD FaceTime Camera",\
// "groupId": "Su/dzw...ccfnY="\
// }\
// ]getCameraDevicesWithPermissions
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getCameraDevicesWithPermissions
ConstgetCameraDevicesWithPermissions():Promise<MediaDeviceInfo[]>, See MediaDeviceInfo for more details.
Deprecated. Use getCameraDevices for better cross-browser compatibility.
After prompting the user for permission, returns an array of camera devices.
Returns
Promise<MediaDeviceInfo[]>
Example
await SignalWire.WebRTC.getCameraDevicesWithPermissions();
// [\
// {\
// "deviceId": "Rug5Bk...4TMhY=",\
// "kind": "videoinput",\
// "label": "HD FaceTime Camera",\
// "groupId": "Su/dzw...ccfnY="\
// }\
// ]getDevices
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getDevices
ConstgetDevices(name?,fullList?):Promise<MediaDeviceInfo[]>, See MediaDeviceInfo for more details.
Enumerates the media input and output devices available on this machine. If name is provided, only the devices of the specified kind are returned. Possible values for name are "camera", "microphone", and "speaker", which respectively correspond to getCameraDevices, getMicrophoneDevices, and getSpeakerDevices.
Parameters
name
DevicePermissionNameDefaults to undefined
Filter for this device category.
fullList
booleanDefaults to false
Set to true to retrieve the raw list as returned by the browser, which might include multiple, duplicate deviceIds for the same group.
Returns
Promise<MediaDeviceInfo[]>
Example
await SignalWire.WebRTC.getDevices("camera", true);
// [\
// {\
// "deviceId": "3c4f97...",\
// "kind": "videoinput",\
// "label": "HD Camera",\
// "groupId": "828fec..."\
// }\
// ]getDevicesWithPermissions
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getDevicesWithPermissions
ConstgetDevicesWithPermissions(kind?,fullList?):Promise<MediaDeviceInfo[]>, See MediaDeviceInfo for more details.
Deprecated. Use getDevices for better cross-browser compatibility.
After prompting the user for permission, returns an array of media input and output devices available on this machine. If kind is provided, only the devices of the specified kind are returned. Possible values for kind are "camera", "microphone", and "speaker", which respectively correspond to getCameraDevicesWithPermissions, getMicrophoneDevicesWithPermissions, and getSpeakerDevicesWithPermissions.
Parameters
kind
DevicePermissionNameDefaults to undefined
Filter for this device category.
fullList
booleanDefaults to false
By default, only devices for which we have been granted permissions are returned. Pass true to obtain a list of devices regardless of permissions. Note that some values such as name and deviceId could be omitted.
Returns
Promise<MediaDeviceInfo[]>
Example
await SignalWire.WebRTC.getDevicesWithPermissions("camera");
// [\
// {\
// "deviceId": "Rug5Bk...4TMhY=",\
// "kind": "videoinput",\
// "label": "HD FaceTime Camera",\
// "groupId": "Su/dzw...ccfnY="\
// }\
// ]getDisplayMedia
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getDisplayMedia
ConstgetDisplayMedia(constraints?):Promise<MediaStream>, See MediaStream for more details.
Prompts the user to share the screen and asynchronously returns a MediaStream object associated with a display or part of it.
Parameters
constraints
MediaStreamConstraints
An optional MediaStreamConstraints object specifying requirements for the returned MediaStream.
Returns
Promise<MediaStream>
Example
await SignalWire.WebRTC.getDisplayMedia(); // MediaStream {id: "HCXy...", active: true, ...}getMicrophoneDevices
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getMicrophoneDevices
ConstgetMicrophoneDevices():Promise<MediaDeviceInfo[]>, See MediaDeviceInfo for more details.
Returns an array of microphone devices that can be accessed on this device (for which we have permissions).
Returns
Promise<MediaDeviceInfo[]>
Example
await SignalWire.WebRTC.getMicrophoneDevices();
// [\
// {\
// "deviceId": "ADciLf...NYgF8=",\
// "kind": "audioinput",\
// "label": "Internal Microphone",\
// "groupId": "rgZgKM...NW1hU="\
// }\
// ]getMicrophoneDevicesWithPermissions
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getMicrophoneDevicesWithPermissions
ConstgetMicrophoneDevicesWithPermissions():Promise<MediaDeviceInfo[]>, See MediaDeviceInfo for more details.
Deprecated. Use getMicrophoneDevices for better cross-browser compatibility.
After prompting the user for permission, returns an array of microphone devices.
Returns
Promise<MediaDeviceInfo[]>
Example
await SignalWire.WebRTC.getMicrophoneDevicesWithPermissions();
// [\
// {\
// "deviceId": "ADciLf...NYgF8=",\
// "kind": "audioinput",\
// "label": "Internal Microphone",\
// "groupId": "rgZgKM...NW1hU="\
// }\
// ]getSpeakerDevices
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getSpeakerDevices
ConstgetSpeakerDevices():Promise<MediaDeviceInfo[]>, See MediaDeviceInfo for more details.
Returns an array of speaker devices that can be accessed on this device (for which we have permissions).
Returns
Promise<MediaDeviceInfo[]>
Example
await SignalWire.WebRTC.getSpeakerDevices();
// [\
// {\
// "deviceId": "ADciLf...NYgF8=",\
// "kind": "audiooutput",\
// "label": "External Speaker",\
// "groupId": "rgZgKM...NW1hU="\
// }\
// ]getSpeakerDevicesWithPermissions
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getSpeakerDevicesWithPermissions
ConstgetSpeakerDevicesWithPermissions():Promise<MediaDeviceInfo[]>, See MediaDeviceInfo for more details.
Deprecated. Use getSpeakerDevices for better cross-browser compatibility.
After prompting the user for permission, returns an array of speaker devices.
Returns
Promise<MediaDeviceInfo[]>
Example
await SignalWire.WebRTC.getSpeakerDevicesWithPermissions();
// [\
// {\
// "deviceId": "ADciLf...NYgF8=",\
// "kind": "audiooutput",\
// "label": "External Speaker",\
// "groupId": "rgZgKM...NW1hU="\
// }\
// ]getSupportedConstraints
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getSupportedConstraints
ConstgetSupportedConstraints():MediaTrackSupportedConstraints
Returns a dictionary whose fields specify the constrainable properties the user agent understands.
Returns
MediaTrackSupportedConstraints
Example
SignalWire.WebRTC.getSupportedConstraints();
// {
// "aspectRatio": true,
// "autoGainControl": true,
// "brightness": true,
// "channelCount": true,
// "colorTemperature": true,
// ...
// }getUserMedia
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
getUserMedia
ConstgetUserMedia(constraints?):Promise<MediaStream>, See MediaStream for more details.
Prompts the user to share one or more media devices and asynchronously returns an associated MediaStream object.
For more information, see MediaDevices.getUserMedia().
Parameters
constraints
MediaStreamConstraints
An optional MediaStreamConstraints object specifying requirements for the returned MediaStream.
Returns
Promise<MediaStream>
Examples
To only request audio media:
await SignalWire.WebRTC.getUserMedia({ audio: true, video: false });
// MediaStream {id: "HCXy...", active: true, ...}To request both audio and video, specifying constraints for the video:
const constraints = {
audio: true,
video: {
width: { min: 1024, ideal: 1280, max: 1920 },
height: { min: 576, ideal: 720, max: 1080 },
},
};
await SignalWire.WebRTC.getUserMedia(constraints);
// MediaStream {id: "EDVk...", active: true, ...}requestPermissions
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
requestPermissions
ConstrequestPermissions(constraints):Promise<void>
Prompts the user to grant permissions for the devices matching the specified set of constraints.
Parameters
constraints
MediaStreamConstraintsRequired
A MediaStreamConstraints object specifying requirements for the permissions.
Returns
Promise<void>
Examples
To only request audio permissions:
await SignalWire.WebRTC.requestPermissions({ audio: true, video: false });To request permissions for both audio and video, specifying constraints for the video:
const constraints = {
audio: true,
video: {
width: { min: 1024, ideal: 1280, max: 1920 },
height: { min: 576, ideal: 720, max: 1080 },
},
};
await SignalWire.WebRTC.requestPermissions(constraints);setMediaElementSinkId
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
setMediaElementSinkId
ConstsetMediaElementSinkId(el,deviceId):Promise<undefined>
Assigns the specified audio output device to the specified HTMLMediaElement. The device with id deviceId must be an audio output device. Asynchronously returns whether the operation succeeded.
Some browsers do not support output device selection. You can check by calling supportsMediaOutput.
Parameters
el
HTMLMediaElement | nullRequired
Target element.
deviceId
stringRequired
Id of the audio output device.
Returns
Promise<undefined>
Example
const el = document.querySelector("video");
const outDevices = await SignalWire.WebRTC.getSpeakerDevicesWithPermissions();
await SignalWire.WebRTC.setMediaElementSinkId(el, outDevices[0].deviceId);
// truestopStream
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
stopStream
ConststopStream(stream?):void
Stops all tracks in a specified stream and fires the ended event for each.
Parameters
stream
MediaStream
The media stream to stop. See MediaStream for more details.
Returns
void
stopTrack
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
stopTrack
ConststopTrack(track):void
Stops a specified track. Similar to MediaStreamTrack.stop(), but also fires the ended event.
Parameters
track
MediaStreamTrackRequired
The media stream track to stop. See MediaStreamTrack for more details.
Returns
void
supportsGetDisplayMedia
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
supportsGetDisplayMedia
ConstsupportsGetDisplayMedia():boolean
Returns whether the current environment supports getDisplayMedia.
Returns
boolean
supportsGetUserMedia
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
supportsGetUserMedia
ConstsupportsGetUserMedia():boolean
Returns whether the current environment supports getUserMedia.
Returns
boolean
supportsMediaDevices
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
supportsMediaDevices
ConstsupportsMediaDevices():boolean
Returns whether the current environment supports the media devices API.
Returns
boolean
supportsMediaOutput
For AI agents: a documentation index is available at the root level at /llms.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
supportsMediaOutput
ConstsupportsMediaOutput():boolean
Returns whether the current environment supports the selection of a media output device.
Returns
boolean
