Overview - JS Client

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

The SDK can be added to your application in the following ways:

Copy
Copied
<!-- Include the Telnyx WEBRTC JS SDK -->
<script
    type="text/javascript"
    src="https://unpkg.com/@telnyx/webrtc@2.9.0/lib/bundle.js">
</script>

Examples

Copy
Copied
// 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');

Note: After pasting the above content, Kindly check and remove any new line added

constructor(options)

Creates a new TelnyxRTC instance with the provided options.

Parameters

NAME TYPE REQUIRED DESCRIPTION
login string optional The username to authenticate with your SIP Connection. login and password will take precedence over login_token for authentication.
login_token string required The JSON Web Token (JWT) to authenticate with your SIP Connection. This is the recommended authentication strategy. See how to create one.
password string optional The password to authenticate with your SIP Connection.
ringbackFile string optional A URL to a wav/mp3 ringback file that will be used when you disable "Generate Ringback Tone" in your SIP Connection.
ringtoneFile string optional A URL to a wav/mp3 ringtone file.

Examples

Authenticating with a JSON Web Token:

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

Note: After pasting the above content, Kindly check and remove any new line added

Authenticating with username and password credentials:

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

Note: After pasting the above content, Kindly check and remove any new line added

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.)

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

Note: After pasting the above content, Kindly check and remove any new line added

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

Copy
Copied
client.remoteElement = 'remoteMedia';

Note: After pasting the above content, Kindly check and remove any new line added

The corresponding HTML:

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

Note: After pasting the above content, Kindly check and remove any new line added

.connected

true if the client is connected to the Telnyx RTC server

Examples

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

Note: After pasting the above content, Kindly check and remove any new line added

.localElement

Gets the local html element.

Examples

Copy
Copied
const client = new TelnyxRTC(options);

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

Note: After pasting the above content, Kindly check and remove any new line added

.mediaConstraints

Audio and video constraints currently used by the client.

Examples

Copy
Copied
const client = new TelnyxRTC(options);

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

Note: After pasting the above content, Kindly check and remove any new line added

.remoteElement

Gets the remote html element.

Examples

Copy
Copied
const client = new TelnyxRTC(options);

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

Note: After pasting the above content, Kindly check and remove any new line added

.speaker

Default audio output device, if set by client.

Examples

Copy
Copied
const client = new TelnyxRTC(options);

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

Note: After pasting the above content, Kindly check and remove any new line added

.checkPermissions(audio, video)

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

Parameters

NAME TYPE DEFAULT REQUIRED DESCRIPTION
audio boolean true required Whether to check for microphone permissions.
video boolean true required Whether to check for webcam permissions.

Examples

Checking for audio and video permissions:

Copy
Copied
const client = new TelnyxRTC(options);

client.checkPermissions();

Note: After pasting the above content, Kindly check and remove any new line added

Checking only for audio permissions:

Copy
Copied
const client = new TelnyxRTC(options);

client.checkPermissions(true, false);

Note: After pasting the above content, Kindly check and remove any new line added

Checking only for video permissions:

Copy
Copied
const client = new TelnyxRTC(options);

client.checkPermissions(false, true);

Note: After pasting the above content, Kindly check and remove any new line added

.connect()

Creates a new connection for exchanging data with the WebRTC server

Examples

Copy
Copied
const client = new TelnyxRTC(options);

client.connect();

Note: After pasting the above content, Kindly check and remove any new line added

.disableMicrophone()

Disables use of the microphone in subsequent calls.

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

Examples

Copy
Copied
const client = new TelnyxRTC(options);

client.disableMicrophone();

Note: After pasting the above content, Kindly check and remove any new line added

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.

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

client.disableMicrophone();

Note: After pasting the above content, Kindly check and remove any new line added

.disableWebcam()

Disables use of the webcam in subsequent calls.

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

Examples

Copy
Copied
const client = new TelnyxRTC(options);

client.disableWebcam();

Note: After pasting the above content, Kindly check and remove any new line added

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

client.disableWebcam();

Note: After pasting the above content, Kindly check and remove any new line added

.disconnect()

Disconnect all active calls

Examples

Copy
Copied
const client = new TelnyxRTC(options);

client.disconnect();

Note: After pasting the above content, Kindly check and remove any new line added

.enableMicrophone()

Enables use of the microphone in subsequent calls.

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

Examples

Copy
Copied
const client = new TelnyxRTC(options);

client.enableMicrophone();

Note: After pasting the above content, Kindly check and remove any new line added

.enableWebcam()

Enables use of the webcam in subsequent calls.

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

Examples

Copy
Copied
const client = new TelnyxRTC(options);

client.enableWebcam();

Note: After pasting the above content, Kindly check and remove any new line added

.getAudioInDevices()

Returns the audio input devices supported by the browser.

Examples

Using async/await:

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

  let result = await client.getAudioInDevices();

  console.log(result);
}

Note: After pasting the above content, Kindly check and remove any new line added

Using ES6 Promises:

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

Note: After pasting the above content, Kindly check and remove any new line added

.getAudioOutDevices()

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

Examples

Using async/await:

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

  let result = await client.getAudioOutDevices();

  console.log(result);
}

Note: After pasting the above content, Kindly check and remove any new line added

Using ES6 Promises:

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

Note: After pasting the above content, Kindly check and remove any new line added

.getDeviceResolutions(deviceId)

Returns supported resolution for the given webcam.

Parameters

NAME TYPE REQUIRED DESCRIPTION
deviceId string required the deviceId from your webcam.

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:

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

Note: After pasting the above content, Kindly check and remove any new line added

Using ES6 Promises:

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

Note: After pasting the above content, Kindly check and remove any new line added

If deviceId is not null

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

Using async/await:

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

Note: After pasting the above content, Kindly check and remove any new line added

Using ES6 Promises:

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

Note: After pasting the above content, Kindly check and remove any new line added

.getDevices()

Returns a list of devices supported by the browser

Examples

Using async/await:

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

Note: After pasting the above content, Kindly check and remove any new line added

Using ES6 Promises:

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

Note: After pasting the above content, Kindly check and remove any new line added

.getVideoDevices()

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

Examples

Using async/await:

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

Note: After pasting the above content, Kindly check and remove any new line added

Using ES6 Promises:

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

Note: After pasting the above content, Kindly check and remove any new line added

.logout()

Alias for .disconnect()

.newCall(options)

Makes a new outbound call.

Parameters

NAME TYPE REQUIRED DESCRIPTION
audio boolean optional Overrides client's default audio constraints. Defaults to true
callerName string optional Name to use as the caller ID name when dialing out to a destination.
callerNumber string optional Number to use as the caller ID when dialing out to a destination. A valid phone number is required for dials out to PSTN numbers.
camId string optional deviceId to use as webcam. Overrides the client's default one.
clientState string optional Telnyx's Call Control client_state. Can be used with Connections with Advanced -> Events enabled.
clientState string should be base64 encoded.
destinationNumber string required Phone number or SIP URI to dial.
iceServers RTCIceServer[] optional Overrides client's default iceServers.
id string optional Custom ID to identify the call. This will be used as the callID in place of the UUID generated by the client.
localElement string | HTMLMediaElement optional Overrides client's default localElement.
localStream MediaStream optional If set, the call will use this stream instead of retrieving a new one.
mediaSettings undefined required Configures media (audio/video) in a call.
micId string optional deviceId to use as microphone. Overrides the client's default one.
onNotification Function optional Overrides client's default telnyx.notification handler for this call.
remoteElement string | HTMLMediaElement optional Overrides client's default remoteElement.
remoteStream MediaStream optional If set, the call will use this stream instead of retrieving a new one.
speakerId string optional deviceId to use as speaker. Overrides the client's default one.
telnyxCallControlId string optional Telnyx Call Control ID, if using Call Control services.
telnyxLegId string optional Telnyx call leg ID, if using Call Control services.
telnyxSessionId string optional Telnyx call session ID, if using Call Control services.
useStereo boolean optional Uses stereo audio instead of mono.
video boolean optional Overrides client's default video constraints. Defaults to false
deviceId string optional

Examples

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

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

Note: After pasting the above content, Kindly check and remove any new line added

You can omit callerNumber when dialing a SIP address:

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

Note: After pasting the above content, Kindly check and remove any new line added

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

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

Note: After pasting the above content, Kindly check and remove any new line added

Error handling

An error will be thrown if destinationNumber is not specified.

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

Note: After pasting the above content, Kindly check and remove any new line added

.off(eventName, callback)

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

Parameters

NAME TYPE REQUIRED DESCRIPTION
eventName string required Event name.
callback Function optional Function handler to be removed.

Examples

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

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

const client = new TelnyxRTC(options);

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

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

Note: After pasting the above content, Kindly check and remove any new line added

.on(eventName, callback)

Attaches an event handler for a specific type of event.

Events

telnyx.ready The client is authenticated and available to use
telnyx.error An error occurred at the session level
telnyx.notification An update to the call or session
telnyx.socket.open The WebSocket connection has been made
telnyx.socket.close The WebSocket connection is set to close
telnyx.socket.error An error occurred at the WebSocket level
telnyx.socket.message The client has received a message through WebSockets

Parameters

NAME TYPE REQUIRED DESCRIPTION
eventName string required Event name.
callback Function required Function to call when the event comes.

Examples

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

Copy
Copied
const client = new TelnyxRTC(options);

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

Note: After pasting the above content, Kindly check and remove any new line added

.setAudioSettings(settings)

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

NAME TYPE REQUIRED DESCRIPTION
settings IAudioSettings required (https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints) object with the addition of micId and micLabel.

Examples

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

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

Note: After pasting the above content, Kindly check and remove any new line added

.setVideoSettings(settings)

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

NAME TYPE REQUIRED DESCRIPTION
settings IVideoSettings required (https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints) object with the addition of camId and camLabel.

Examples

Set webcam by id and label with 720p resolution.

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

Note: After pasting the above content, Kindly check and remove any new line added

.webRTCInfo()

Checks if the running browser has support for TelnyRTC

Examples

Check if your browser supports TelnyxRTC

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

Note: After pasting the above content, Kindly check and remove any new line added

Error handling

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

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

Note: After pasting the above content, Kindly check and remove any new line added

.webRTCSupportedBrowserList()

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.

CHROME FIREFOX SAFARI EDGE
Android - -
iOS x
Linux x -
MacOS x - x -
Windows x - -

Legend

x supports audio and video - supports only audio not supported

Examples

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

Note: After pasting the above content, Kindly check and remove any new line added