Skip to main content

WebRTC JS Client

The TelnyxRTC client connects your application to the Telnyx backend, enabling you to make outgoing calls and handle incoming calls.

Examples

// Initialize the client
const client = new TelnyxRTC({
// Use a JWT to authenticate (recommended)
login_token: login_token,
// or use your Connection credentials
// login: username,
// password: password,
});

// Attach event listeners
client
.on('telnyx.ready', () => console.log('ready to call'))
.on('telnyx.notification', (notification) => {
console.log('notification:', notification)
});

// Connect and login
client.connect();

// You can call client.disconnect() when you're done.
Note: When you call `client.disconnect()` you need to remove all ON event methods you've had attached before.

// Disconnecting and Removing listeners.
client.disconnect();
client.off('telnyx.ready')
client.off('telnyx.notification');

Hierarchy

  • default

    TelnyxRTC

Table of contents

Constructors

Accessors

Methods

Constructors

constructor

new TelnyxRTC(options)

Creates a new TelnyxRTC instance with the provided options.

Parameters

NameTypeDescription
optionsIClientOptionsOptions for initializing a client

Examples

Authenticating with a JSON Web Token:

const client = new TelnyxRTC({
login_token: login_token,
});

Authenticating with username and password credentials:

const client = new TelnyxRTC({
login: username,
password: password,
});

Custom ringtone and ringback

Custom ringback and ringtone files can be a wav/mp3 in your local public folder or a file hosted on a CDN, ex: https://cdn.company.com/sounds/call.mp3.

To use the ringbackFile, make sure the "Generate Ringback Tone" option is disabled in your Telnyx Portal connection configuration (Inbound tab.)

const client = new TelnyxRTC({
login_token: login_token,
ringtoneFile: './sounds/incoming_call.mp3',
ringbackFile: './sounds/ringback_tone.mp3',
});

To hear/view calls in the browser, you'll need to specify an HTML media element:

client.remoteElement = 'remoteMedia';

The corresponding HTML:

<audio id="remoteMedia" autoplay="true" />
<!-- or for video: -->
<!-- <video id="remoteMedia" autoplay="true" playsinline="true" /> -->

Overrides

TelnyxRTCClient.constructor

Accessors

connected

get connected(): boolean

true if the client is connected to the Telnyx RTC server

Returns

boolean

Example

const client = new TelnyxRTC(options);
console.log(client.connected); // => false

Inherited from

TelnyxRTCClient.connected


localElement

get localElement(): string | Function | HTMLMediaElement

Gets the local html element.

Returns

string | Function | HTMLMediaElement

Example

const client = new TelnyxRTC(options);

console.log(client.localElement);
// => HTMLMediaElement

Inherited from

TelnyxRTCClient.localElement

set localElement(tag): void

Sets the local html element that will receive the local stream.

Parameters

NameType
tagstring | Function | HTMLMediaElement

Returns

void

Example

const client = new TelnyxRTC(options);
client.localElement = 'localElementMediaId';

Inherited from

TelnyxRTCClient.localElement


mediaConstraints

get mediaConstraints(): Object

Audio and video constraints currently used by the client.

Returns

Object

NameType
audioboolean | MediaTrackConstraints
videoboolean | MediaTrackConstraints

Examples

const client = new TelnyxRTC(options);

console.log(client.mediaConstraints);
// => { audio: true, video: false }

Inherited from

TelnyxRTCClient.mediaConstraints


remoteElement

get remoteElement(): string | Function | HTMLMediaElement

Gets the remote html element.

Returns

string | Function | HTMLMediaElement

Example

const client = new TelnyxRTC(options);

console.log(client.remoteElement);
// => HTMLMediaElement

Inherited from

TelnyxRTCClient.remoteElement

set remoteElement(tag): void

Sets the remote html element that will receive the remote stream.

Parameters

NameType
tagstring | Function | HTMLMediaElement

Returns

void

Example

const client = new TelnyxRTC(options);
client.remoteElement = 'remoteElementMediaId';

Inherited from

TelnyxRTCClient.remoteElement


speaker

get speaker(): string

Default audio output device, if set by client.

Returns

string

Example

const client = new TelnyxRTC(options);

console.log(client.speaker);
// => "abc123xyz"

Inherited from

TelnyxRTCClient.speaker

set speaker(deviceId): void

Sets the default audio output device for subsequent calls.

Parameters

NameType
deviceIdstring

Returns

void

Example

let result = await client.getAudioOutDevices();

if (result.length) {
client.speaker = result[1].deviceId;
}

Inherited from

TelnyxRTCClient.speaker

Methods

checkPermissions

checkPermissions(audio?, video?): Promise<boolean>

Checks if the browser has the permission to access mic and/or webcam

Parameters

NameTypeDefault valueDescription
audiobooleantrueWhether to check for microphone permissions.
videobooleantrueWhether to check for webcam permissions.

Returns

Promise<boolean>

Examples

Checking for audio and video permissions:

const client = new TelnyxRTC(options);

client.checkPermissions();

Checking only for audio permissions:

const client = new TelnyxRTC(options);

client.checkPermissions(true, false);

Checking only for video permissions:

const client = new TelnyxRTC(options);

client.checkPermissions(false, true);

Inherited from

TelnyxRTCClient.checkPermissions


connect

connect(): Promise<void>

Creates a new connection for exchanging data with the WebRTC server

Returns

Promise<void>

Examples

const client = new TelnyxRTC(options);

client.connect();

Inherited from

TelnyxRTCClient.connect


disableMicrophone

disableMicrophone(): void

Disables use of the microphone in subsequent calls.

Note: This setting will be ignored if audio: true is specified when creating a new call.

Returns

void

Examples

const client = new TelnyxRTC(options);

client.disableMicrophone();

Keep in mind that new calls will fail if both the microphone and webcam is disabled. Make sure that the webcam is manually enabled, or video: true is specified before disabling the microphone.

const client = new TelnyxRTC({
...options,
video: true
});

client.disableMicrophone();

Inherited from

TelnyxRTCClient.disableMicrophone


disableWebcam

disableWebcam(): void

Disables use of the webcam in subsequent calls.

Note: This method will disable the video even if video: true is specified.

Returns

void

Examples

const client = new TelnyxRTC(options);

client.disableWebcam();
const client = new TelnyxRTC({
...options,
video: true
});

client.disableWebcam();

Deprecated

Inherited from

TelnyxRTCClient.disableWebcam


disconnect

disconnect(): Promise<void>

Disconnect all active calls

Returns

Promise<void>

Examples

const client = new TelnyxRTC(options);

client.disconnect();

Inherited from

TelnyxRTCClient.disconnect


enableMicrophone

enableMicrophone(): void

Enables use of the microphone in subsequent calls.

Note: This setting will be ignored if audio: false is specified when creating a new call.

Returns

void

Examples

const client = new TelnyxRTC(options);

client.enableMicrophone();

Inherited from

TelnyxRTCClient.enableMicrophone


enableWebcam

enableWebcam(): void

Enables use of the webcam in subsequent calls.

Note: This setting will be ignored if video: false is specified when creating a new call.

Returns

void

Examples

const client = new TelnyxRTC(options);

client.enableWebcam();

Deprecated

Inherited from

TelnyxRTCClient.enableWebcam


getAudioInDevices

getAudioInDevices(): Promise<MediaDeviceInfo[]>

Returns the audio input devices supported by the browser.

Returns

Promise<MediaDeviceInfo[]>

Promise with an array of MediaDeviceInfo

Examples

Using async/await:

async function() {
const client = new TelnyxRTC(options);

let result = await client.getAudioInDevices();

console.log(result);
}

Using ES6 Promises:

client.getAudioInDevices().then((result) => {
console.log(result);
});

Inherited from

TelnyxRTCClient.getAudioInDevices


getAudioOutDevices

getAudioOutDevices(): Promise<MediaDeviceInfo[]>

Returns the audio output devices supported by the browser.

Browser Compatibility Note: Firefox has yet to fully implement audio output devices. As of v63, this feature is behind the user preference media.setsinkid.enabled. See: https://bugzilla.mozilla.org/show_bug.cgi?id=1152401#c98

Returns

Promise<MediaDeviceInfo[]>

Promise with an array of MediaDeviceInfo

Examples

Using async/await:

async function() {
const client = new TelnyxRTC(options);

let result = await client.getAudioOutDevices();

console.log(result);
}

Using ES6 Promises:

client.getAudioOutDevices().then((result) => {
console.log(result);
});

Inherited from

TelnyxRTCClient.getAudioOutDevices


getDeviceResolutions

getDeviceResolutions(deviceId): Promise<any[]>

Returns supported resolution for the given webcam.

Parameters

NameTypeDescription
deviceIdstringthe deviceId from your webcam.

Returns

Promise<any[]>

Examples

If deviceId is null

  1. if deviceId is null and you don't have a webcam connected to your computer, it will throw an error with the message "Requested device not found".

  2. if deviceId is null and you have one or more webcam connected to your computer, it will return a list of resolutions from the default device set up in your operating system.

Using async/await:

async function() {
const client = new TelnyxRTC(options);
let result = await client.getDeviceResolutions();
console.log(result);
}

Using ES6 Promises:

client.getDeviceResolutions().then((result) => {
console.log(result);
});

If deviceId is not null

it will return a list of resolutions from the deviceId sent.

Using async/await:

async function() {
const client = new TelnyxRTC(options);
let result = await client.getDeviceResolutions(deviceId);
console.log(result);
}

Using ES6 Promises:

client.getDeviceResolutions(deviceId).then((result) => {
console.log(result);
});

Deprecated

Inherited from

TelnyxRTCClient.getDeviceResolutions


getDevices

getDevices(): Promise<MediaDeviceInfo[]>

Returns a list of devices supported by the browser

Returns

Promise<MediaDeviceInfo[]>

Examples

Using async/await:

async function() {
const client = new TelnyxRTC(options);
let result = await client.getDevices();
console.log(result);
}

Using ES6 Promises:

client.getDevices().then((result) => {
console.log(result);
});

Inherited from

TelnyxRTCClient.getDevices


getIsRegistered

getIsRegistered(): Promise<boolean>

Get the registration state of the client

Returns

Promise<boolean>

Promise

Inherited from

TelnyxRTCClient.getIsRegistered


getVideoDevices

getVideoDevices(): Promise<MediaDeviceInfo[]>

Returns a list of video devices supported by the browser (i.e. webcam).

Returns

Promise<MediaDeviceInfo[]>

Promise with an array of MediaDeviceInfo

Examples

Using async/await:

async function() {
const client = new TelnyxRTC(options);
let result = await client.getVideoDevices();
console.log(result);
}

Using ES6 Promises:

client.getVideoDevices().then((result) => {
console.log(result);
});

Deprecated

Inherited from

TelnyxRTCClient.getVideoDevices


logout

logout(): void

Alias for .disconnect()

Returns

void

Deprecated

Inherited from

TelnyxRTCClient.logout


newCall

newcall(options): call

Makes a new outbound call.

Parameters

NameTypeDescription
optionsicalloptionsOptions object for a new call.

Returns

call

The new outbound Call object.

Examples

Making an outbound call to +1 856-444-0362 using default values from the client:

const call = client.newCall({
destinationNumber: '+18564440362',
callerNumber: '+15551231234'
});

You can omit callerNumber when dialing a SIP address:

const call = client.newCall({
destinationNumber: 'sip:example-sip-username@voip-provider.example.net'
});

If you are making calls from one Telnyx connection to another, you may specify just the SIP username:

const call = client.newCall({
destinationNumber: 'telnyx-sip-username' // This is equivalent to 'sip:telnyx-sip-username@sip.telnyx.com'
});

Error handling

An error will be thrown if destinationNumber is not specified.

const call = client.newCall().catch(console.error);
// => `destinationNumber is required`

Setting Custom Headers


client.newCall({
destinationNumber: '18004377950',

callerNumber: '155531234567',

customHeaders: [ {name: "X-Header", value: "value" } ]
});

Setting Preferred Codec

You can pass preferred_codecs to the newCall method to set codec preference during the call.

preferred_codecs is a sub-array of the codecs returned by RTCRtpReceiver.getCapabilities('audio')

const allCodecs = RTCRtpReceiver.getCapabilities('audio').codecs;

const PCMACodec = allCodecs.find((c) => c.mimeType.toLowerCase().includes('pcma'));

client.newCall({
destinationNumber: 'xxx',
preferred_codecs: [PCMACodec],
});

ICE Candidate Prefetching

ICE candidate prefetching can be enabled by passing prefetchIceCandidates to the newCall method. example:

client.newCall({
destinationNumber: 'xxx',
prefetchIceCandidates: true,
});

Overrides

TelnyxRTCClient.newCall


off

off(eventname, callback?): telnyxrtc

Removes an event handler that were attached with .on(). If no handler parameter is passed, all listeners for that event will be removed.

Parameters

NameTypeDescription
eventNamestringEvent name.
callback?FunctionFunction handler to be removed.

Returns

telnyxrtc

The client object itself.

Note: a handler will be removed from the stack by reference so make sure to use the same reference in both .on() and .off() methods.

Examples

Subscribe to the telnyx.error and then, remove the event handler.

const errorHandler = (error) => {
// Log the error..
}

const client = new TelnyxRTC(options);

client.on('telnyx.error', errorHandler)

// .. later
client.off('telnyx.error', errorHandler)

Inherited from

TelnyxRTCClient.off


on

on(eventname, callback): telnyxrtc

Attaches an event handler for a specific type of event.

Events

telnyx.readyThe client is authenticated and available to use
telnyx.errorAn error occurred at the session level
telnyx.notificationAn update to the call or session
telnyx.socket.openThe WebSocket connection has been made
telnyx.socket.closeThe WebSocket connection is set to close
telnyx.socket.errorAn error occurred at the WebSocket level
telnyx.socket.messageThe client has received a message through WebSockets

Parameters

NameTypeDescription
eventNamestringEvent name.
callbackFunctionFunction to call when the event comes.

Returns

telnyxrtc

The client object itself.

Examples

Subscribe to the telnyx.ready and telnyx.error events.

const client = new TelnyxRTC(options);

client.on('telnyx.ready', (client) => {
// Your client is ready!
}).on('telnyx.error', (error) => {
// Got an error...
})

Inherited from

TelnyxRTCClient.on


setAudioSettings

setAudioSettings(settings): Promise<MediaTrackConstraints>

Sets the default audio constraints for your client. See here for further details.

Note: It's a common behaviour, in WebRTC applications, to persist devices user's selection to then reuse them across visits. Due to a Webkit’s security protocols, Safari generates random deviceId on each page load. To avoid this issue you can specify two additional properties micId and micLabel in the constraints input parameter. The client will use these values to assure the microphone you want to use is available by matching both id and label with the device list retrieved from the browser.

Parameters

NameTypeDescription
settingsIAudioSettingsMediaTrackConstraints object with the addition of micId and micLabel.

Returns

Promise<MediaTrackConstraints>

Promise<MediaTrackConstraints> Audio constraints applied to the client.

Examples

Set microphone by id and label with the echoCancellation flag turned off:

// within an async function
const constraints = await client.setAudioSettings({
micId: '772e94959e12e589b1cc71133d32edf543d3315cfd1d0a4076a60601d4ff4df8',
micLabel: 'Internal Microphone (Built-in)',
echoCancellation: false
})

Inherited from

TelnyxRTCClient.setAudioSettings


setVideoSettings

setVideoSettings(settings): Promise<MediaTrackConstraints>

Sets the default video constraints for your client. See here for further details.

Note: It's a common behaviour, in WebRTC applications, to persist devices user's selection to then reuse them across visits. Due to a Webkit’s security protocols, Safari generates random deviceId on each page load. To avoid this issue you can specify two additional properties camId and camLabel in the constraints input parameter. The client will use these values to assure the webcam you want to use is available by matching both id and label with the device list retrieved from the browser.

Parameters

NameTypeDescription
settingsIVideoSettingsMediaTrackConstraints object with the addition of camId and camLabel.

Returns

Promise<MediaTrackConstraints>

Promise<MediaTrackConstraints> Video constraints applied to the client.

Examples

Set webcam by id and label with 720p resolution.

// within an async function
const constraints = await client.setVideoSettings({
camId: '882e94959e12e589b1cc71133d32edf543d3315cfd1d0a4076a60601d4ff4df8',
camLabel: 'Default WebCam (Built-in)',
width: 1080,
height: 720
})

Deprecated

Inherited from

TelnyxRTCClient.setVideoSettings


webRTCInfo

Static webRTCInfo(): string | IWebRTCInfo

Checks if the running browser has support for TelnyRTC

Returns

string | IWebRTCInfo

An object with WebRTC browser support information or a string error message.

Examples

Check if your browser supports TelnyxRTC

const info = TelnyxRTC.webRTCInfo();
const isWebRTCSupported = info.supportWebRTC;
console.log(isWebRTCSupported); // => true

Error handling

An error message will be returned if your browser doesn't support TelnyxRTC

const info = TelnyxRTC.webRTCInfo();
if (!info.supportWebRTC) {
console.error(info) // => 'This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()'
}

webRTCSupportedBrowserList

Static webRTCSupportedBrowserList(): IWebRTCSupportedBrowser[]

Returns the WebRTC supported browser list.

The following table indicates the browsers supported by TelnyxRTC. We support the most recent (N) versions of these browsers unless otherwise indicated.

ChromeFirefoxSafariEdge
Android[-][-][ ][ ]
iOS[ ][ ][x][ ]
Linux[x][-][ ][ ]
MacOS[x][-][x][-]
Windows[x][-][ ][-]

Legend

[x] supports audio and video [-] supports only audio [ ] not supported

Returns

IWebRTCSupportedBrowser[]

An array with supported operational systems and browsers.

Examples

const browserList = TelnyxRTC.webRTCSupportedBrowserList();
console.log(browserList) // => [{"operationSystem": "Android", "supported": [{"browserName": "Chrome", "features": ["video", "audio"], "supported": "full"},{...}]