Browser SDK Reference

Plivo Browser SDK allows you to make and receive calls using Plivo applications directly from any web browser that supports webRTC. Using our SDK you can create applications like Click to Call, Conferencing Apps and even Webphones.

The Browser SDK codebase is publicly available. Read this support page to see what benefits making the codebase available offers to developers.

Browser SDK supports Typescript. For more information about the benefits of Browser SDK with Typescript, read this support page.

Supported browsers

This table shows the browsers supported by the Plivo Browser SDK.

Chrome and Firefox: We support the most recent and previous 10 versions.
Safari: We support the most recent and previous five versions.

Chrome Firefox Safari Chromium
macOS
Windows **
Linux ** ***
iOS * * *
Android **

* Unlike Safari for iOS, Chrome and Firefox for iOS do not have access to WebRTC APIs.
** Safari for Windows and Linux are not supported.
*** Edge for Linux is not supported.

Note: On mobile browsers, Browser SDK functionality may be compromised due to limitations imposed by browsers. These limitations include inability to maintain call connectivity if the browser moves to the background, inability to receive incoming call notifications in case the browser was in background, and inability to handle GSM call interruptions. As a result, we highly recommend that you evaluate our mobile SDKs (iOS, Android) while creating mobile voice apps for better user experience.

Read more details on limitations and variations.

Try out the demo — get started with examples.

Including the Plivo Browser SDK

You can include the Plivo-Browser-SDK NPM package as a dependency in your project. Use the below command:

npm install plivo-browser-sdk --save

Also, you can include the latest Plivo-Browser-SDK Beta NPM package using the below command:

npm install plivo-browser-sdk@beta

You can include the plivo javascript file as shown below directly on your webpage

<script type="text/javascript" src="https://cdn.plivo.com/sdk/browser/v2/plivo.min.js"/> 

Note: We do not recommend this approach because any recent changes to our SDK will be applied to your production apps automatically without going through your build process and could lead to unexpected behavior for your customers.


To mitigate this risk, every new release is first pushed to this beta CDN link before being merged to the master: <https://cdn.plivo.com/sdk/browser/v2/plivobeta.min.js>

Alternatively, you can include a specific release in your app by using it’s specific CDN link. We continue to make our past releases URI accessible and immutable, unless explicitly stated. You can find the latest links on the Changelog Page.

Initializing the plivoBrowserSdk Object

The plivoBrowserSdk object needs to be initialized.

var options = {
"debug":"DEBUG",
"permOnClick":true,
"enableTracking":true,
"closeProtection":true,
"maxAverageBitrate":48000
};
var plivoBrowserSdk = new window.Plivo(options);

For more explanation on options see the Configuration section.

Event registration

Pass function references to the events produced from the SDK. This is where your UI manipulation should handle the call flows.

plivoBrowserSdk.client.on('onWebrtcNotSupported', onWebrtcNotSupported);
plivoBrowserSdk.client.on('onLogin', onLogin);
plivoBrowserSdk.client.on('onLogout', onLogout);
plivoBrowserSdk.client.on('onLoginFailed', onLoginFailed);
plivoBrowserSdk.client.on('onCallRemoteRinging', onCallRemoteRinging);
plivoBrowserSdk.client.on('onCallConnected', onCallConnected);
plivoBrowserSdk.client.on('onIncomingCallCanceled', onIncomingCallCanceled);
plivoBrowserSdk.client.on('onCallFailed', onCallFailed);
plivoBrowserSdk.client.on('onCallAnswered', onCallAnswered);
plivoBrowserSdk.client.on('onMediaConnected', onMediaConnected);
plivoBrowserSdk.client.on('onCallTerminated', onCallTerminated);
plivoBrowserSdk.client.on('onCalling', onCalling);
plivoBrowserSdk.client.on('onIncomingCall', onIncomingCall);
plivoBrowserSdk.client.on('onMediaPermission', onMediaPermission);
plivoBrowserSdk.client.on('mediaMetrics',mediaMetrics);
plivoBrowserSdk.client.on('onConnectionChange',onConnectionChange);
plivoBrowserSdk.client.on('onDtmfReceived',onDtmfReceived);
plivoBrowserSdk.client.on('remoteAudioStatus', remoteAudioStatus);
plivoBrowserSdk.client.on('onNoiseReductionReady', onNoiseReductionReady);
plivoBrowserSdk.client.on('onWebSocketConnected', onWebSocketConnected);

Registering using your Plivo endpoint

Register using your Plivo endpoint credentials

var username = 'johndoe12345';
var password = '<pswd>';
plivoBrowserSdk.client.login(username, password);

Making a call

Making a call to any number/SIP endpoint. The application attached to the registered endpoint should have an answer URL that will return the correct <Dial> element.

var dest = "jane1234@phone.plivo.com";
var extraHeaders = {'X-PH-Test1': 'test1', 'X-PH-Test2': 'test2'};
plivoBrowserSdk.client.call(dest, extraHeaders);

Accepting a call

This is how an incoming call should be answered when an onIncomingCall event is received.

plivoBrowserSdk.client.answer(callUUID)

callUUID is passed in the onIncomingCall event callback, as we describe below.

Sending DTMF

This snippet sends a DTMF tone when in a phone call.

plivoBrowserSdk.client.sendDtmf("1");

Configuration parameters

Attribute Description Allowed Values Default Value
debug Enable debug message in JS log OFF, ERROR, WARN, INFO, DEBUG, ALL INFO
permOnClick Set to true if you want to ask for mic permission just before call connection. Otherwise it will be asked only on page load. true/false false
dtmfOptions This parameter can be used to select between "inband" and/or "outband" DTMF. {sendDtmfType: ["inband"] } / {sendDtmfType: ["outband"] } / {sendDtmfType: ["inband","outband"] } {sendDtmfType: ["inband","outband"]}
audioConstraints Audio constraints object that will be passed to webRTC getUserMedia(). Audio constraints values are browser specific. Refer: MediaTrackConstraints {}
enableTracking Set to true if you want to get mediaMetrics events and enable call quality tracking. true/false true
Note: enableTracking will be deprecated as part of the next major update. Please use use enableQualityTracking instead.
enableQualityTracking

This parameter can be used to enable and disable two functionalities:

mediaMetrics events enables the Client device to display local call issues such as broken audio to the user.

Call quality tracking enables Plivo to capture and display call quality data in Call Insights.

When set to all both MediaMetrics events and call quality tracking is enabled.

When set to remoteonly only call quality tracking is enabled.

When set to localonly only MediaMetrics events are enabled.

When set to none both MediaMetrics events and call quality tracking are disabled.

all, remoteonly, localonly, none all
Note: If enableQualityTracking is configured with a nondefault value, it overrides any configuration of enableTracking.
closeProtection Set to true to get a dialog prompt while closing the app when the call is in progress (ringing state or answered state). true, false false
dscp Set to true to enable QoS in voice traffic. Differentiated Services field in the packet headers for all WebRTC traffic. Note: dscp is supported only in Chrome. true, false true
allowMultipleIncomingCalls

When set to true there can be multiple calls ringing at the same time.

1. The onIncomingCall event will be fired for every incoming call.

2. When an incoming call is accepted, other ringing calls (if any) will be either rejected or ignored depending on the option passed to answer function automatically.

3. When an incoming call is rejected or ignored, other ringing calls (if any) will continue ringing.

There can only be one active answered call at any given moment.

1. When an incoming call is accepted, the in-progress answered call will be disconnected automatically.

2. When an incoming call is rejected or ignored, the in-progress answered call will continue without any interruption.

When set to false incoming calls are silently rejected if the endpoint is engaged in an active call or if another call is ringing.

true, false false
clientRegion Initialization options to set and route calls to specific MediaServer POPs ["usa_west", "usa_east", "australia", "europe", "asia", "south_america", "south_asia"] -
Note: If clientRegion is not defined, the nearest Plivo data center (PoP) will be picked based on the Browser SDK client registered IP address.
enableNoiseReduction Reduces background noise during ongoing calls. true, false true
usePlivoStunServers Indicates that Plivo will strive to establish the connection with two parallel STUN servers, and the connection will be established promptly upon receiving a response from either server. true, false false
useDefaultAudioDevice Determines whether the system's default input/output devices are utilized following the addition or removal of an audio device. If not, the recently added device will be utilized for both input and output. true, false false
stopAutoRegisterOnConnect When set to true, the login() method will only establish a connection to the Plivo servers but will not register the SDK. To complete the registration process, you will need to manually invoke the register() method. true, false false
captureSDKCrashOnly When set to true, the SDK will only capture and sync crashes related to the SDK code, avoiding App side errors being pushed to Plivo servers. true, false false
maxAverageBitrate

Used to control your application’s bandwidth consumption for calls.

A higher maxAverageBitrate value may result in more bandwidth consumption, but also better audio quality.

Lowering the maxAverageBitrate impacts call quality, as audio is compressed to a greater extent to reduce bandwidth consumption.

This parameter only applies to calls using the Opus codec. See RFC-7587 section 7.1 for more info.

8000 - 48000 48000
registrationRefreshTimer A parameter where we allow users to set the value for refreshing the registration of the SDK. 100 - 86400 seconds 120 seconds

Variables

Variable Description
version Returns current version of the Plivo SDK.
isLoggedIn Returns true if the user is logged in and false otherwise.

Methods

Method Description
login(username, password) Register a Plivo endpoint.
logout() Log out from the registered endpoint.
call(number, extraHeaders)

Call a number or SIP address. 'number' takes a String value and 'extraHeaders' takes a JSON object. Extra headers should start with X-PH.
Example of 'extraHeaders': {'X-PH-Test1': 'test1', 'X-PH-Test2': 'test2'}

Note: Browser SDK supports specific characters in extra headers. Those include [A-Z], [a,z], [0-9]. Additionally, special characters +-_() are also allowed. Any other characters apart from these are ignored by Browser SDK.

answer(callUUID, actionOnOtherIncomingCalls) Answer an incoming call.
When callUUID is given, the SDK will attempt to answer the incoming call identified by it.
When callUUID is not given, the SDK will attempt to answer the most recent ringing call.
When callUUID is invalid, the SDK will return false with an error log.
actionOnOtherIncomingCalls is Optional -
Possible string values:
reject — This is the default value. Other incoming calls (if any) are rejected.
ignored — Other incoming calls (if any) stop ringing locally but ring for the caller. These incoming calls cannot be answered after ignored.
letring — Other incoming calls ring silently in local and continue to ring for the caller. These incoming calls can be answered until they stop ringing.
hangup() Hang up the ongoing call.
reject(callUUID) Reject an incoming call.
When callUUID is given, the SDK attempts to reject the ringing call it identifies. When callUUID is not given or an invalid callUUID is given, the SDK attempts to answer the most recent ringing call.
ignore(callUUID) Stops the incoming sound (ring) and sets the call state to ignored, but does not send a hangup message to the dialing party. The incoming call keeps ringing for the called party until the call times out.
When callUUID is given, the SDK attempts to ignore the incoming call it identifies. When callUUID is not given or an invalid callUUID is given, the SDK attempts to ignore the most recent ringing call.
sendDtmf(digit) Send the digits as DTMF.
digit can be any numeric one-character strings or "*" or "#".
mute() Mutes the mic.
unmute() Unmutes the mic.
setRingTone(url or boolean) Configures the ringtone played locally by the browser for incoming calls.
true (default) — default tone is played during incoming call
false — no ringtone is played during incoming call
url — media at the URL is played during incoming call
setRingToneBack(url or boolean) Use this function to configure the ringtone played locally by the browser when an outgoing call starts ringing.
true (default) — the default tone is played when an outbound call rings. Note that ringtone and pre-answer announcements passed by Plivo’s media servers will not be played.
false — ringtone and pre-answer announcements received from Plivo’s media servers are played
url — remote ringtone is paused and media URL passed is played during outbound call ringing status.
setConnectTone(boolean) true (default) — Dial tone plays while the call is being connected.
false — No dial tone plays.
setDebug(debug) Set the log level of the SDK. Allowed values: OFF, ERROR, WARN, INFO, DEBUG, ALL
getPeerConnection() Returns a RTCPeerConnection object.
Example: { status: ’success’, pc: RTCPeerConnection }
submitCallQualityFeedback(callUUID, starRating, issues, note, sendConsoleLogs) callUUID is a mandatory string parameter used to identify the call the feedback belongs to. You can get the callUUID from getCallUUID() or getLastCallUUID().
starRating is a mandatory integer parameter with a value from 1 to 5. For a score from 1 to 4, issues parameter is mandatory; it is optional for a score of 5.
issues is an array and must have at least one of these reasons for a starRating value from 1 to 4: AUDIO_LAG, BROKEN_AUDIO, CALL_DROPPPED, CALLERID_ISSUES, DIGITS_NOT_CAPTURED, ECHO, HIGH_CONNECT_TIME, LOW_AUDIO_LEVEL, ONE_WAY_AUDIO, ROBOTIC_AUDIO, OTHERS
note is an optional string attribute for user remarks.
sendConsoleLogs is an boolean optional paramter with default value false. Set to true to enable Plivo’s team to collect and analyze Browser SDK’s logs so we can better understand the issue.
getCallUUID() Returns a string call UUID if a call is active, else returns null.
getLastCallUUID() Returns the call UUID of the latest answered call. Useful if you want to send feedback for the last call.
startNoiseReduction() Starts noise reduction.
stopNoiseReduction() Stops noise reduction.
isConnected() This function returns a boolean value indicating whether the WebSocket is connected. It serves to check the status of the WebSocket connection before attempting to re-initiate it.
isConnecting() This function returns a boolean value indicating whether the WebSocket connection is currently in progress. It serves to check the status of the WebSocket connection before attempting to re-initiate it.
isRegistered() This function returns a boolean value indicating whether the registration is sucessful.
register() This method will register the SDK once it is connected to Plivo servers. The onWebSocketConnected event will be triggered when the SDK is successfully connected to the Plivo servers.
unregister() This method will unregister the SDK while keeping it connected to Plivo servers.
disconnect() This method will disconnect the SDK from Plivo servers and unregister it.
getContactUri() Returns a contact URI string that can be used to redirect a call to different tabs, typically used in multi-tab scenarios.
redirect(uri) This method allows redirecting a call to the specified URI, directing it to the required tab.
getCurrentSession() Returns the current active session. If there is no active session, it returns null; otherwise, it returns the active session object.
setIdentifier() Helps to uniquely identify a tab.
webRTC() Returns true if webRTC is supported and false if not.

Methods in Audio Device API

Method Description
availableDevices(filter) Returns promise that resolves with an array of device objects.
The filter parameter is optional and takes a String value. Pass input to filter by input audio devices, output to filter by output audio devices, null to get all audio devices.
Wrapper for MediaDevices.enumerateDevices() that filters out non-audio devices.
Note :
1. When media permission is not given by users, labels do not appear. In this case, to get labels for a device, use revealAudioDevices(), then call availableDevices().
2. Device ID remains the same, unless the domain changes or private browsing mode is used. Refer: MediaDeviceInfo.deviceId
3. Device Enumerator API from browser can also be used to list devices IDs and labels — enumerateDevices.
revealAudioDevices(arg) Returns a promise that resolves with success if user allows media permission. If returnStream is passed as an argument, the promise will resolve with the MediaStream object.

Objects in Audio Device API

Object Methods and Parameters Description
microphoneDevices

set(deviceID)

get()

reset()

set takes the deviceID parameter and sets it as the default input device for taking input audio. The deviceID parameter is mandatory and takes a String value.

get returns the input audio device ID that is set.

reset removes any input audio device ID that is already set.

speakerDevices

set(deviceID)

get()

reset()

media(source)

set sets the audioDevice ID as default speaker device for DTMF and remote audio. The deviceID parameter is mandatory and takes a String value.

get returns the speaker device ID that is set.

reset removes any speaker device ID that is already set.

media takes dtmf or ringback as a source parameter and returns the corresponding HTML audio element. This parameter is mandatory.

ringtoneDevices

set(deviceID)

get()

reset()

media

set takes the deviceID parameter and sets it as the ringtone device for playing an incoming call ringtone. The deviceID parameter is mandatory and takes a String value.

get returns the ringtone device ID that is set.

reset removes any ringtone device ID that is already set.

media returns the HTML audio element for playing the ringtone.

Events

Event Description
onLogin Occurs when a login is successful.
onLoginFailed(cause) Occurs when a login has failed. cause returns the login failure reason.
onLogout Occurs when a logout is successful.
onCalling Occurs when a call is initiated.
onCallRemoteRinging(callInfo) Occurs when the call is initiated towards the remote end from the plivo servers during an outbound call.
onCallConnected(callInfo) Occurs when the PSTN remote end starts ringing during an outbound call. This event is not applicable for Multi-Party Call (MPC) or Conference based calls.
onCallAnswered(callInfo) Occurs when an outbound or an inbound call is answered.
onMediaConnected(callInfo) Occurs when the media connection is established.
onCallTerminated(hangupInfo, callInfo) Occurs when an outbound or an inbound call has ended.
remoteAudioStatus(bool) Provides a boolean value indicating audio activity from the remote party. True denotes the reception of an audio packet, while False indicates the absence of audio packet reception from the other end. This feature is exclusively accessible in conference or Multi-Party Call (MPC) calls.
onIncomingCall(callerID, extraHeaders, callInfo, callerName) Occurs when there is an incoming call. callerID provides the caller ID, callerName provides the caller name set by the initiator of the call, and extraHeaders return the X-Headers from Plivo.
onIncomingCallCanceled(callInfo) Occurs when an incoming call is canceled by the caller.
onIncomingCallIgnored(callInfo) Occurs when an incoming call is successfully ignored using the ignore(callUUID) function.
onCallFailed(cause, callInfo) Occurs when an outbound or an inbound call fails. cause returns the reason for call failing.
Possible error events:
INVALID_ACCESS_TOKEN
INVALID_ACCESS_TOKEN_HEADER
INVALID_ACCESS_TOKEN_ISSUER
INVALID_ACCESS_TOKEN_SUBJECT
ACCESS_TOKEN_NOT_VALID_YET
ACCESS_TOKEN_EXPIRED
INVALID_ACCESS_TOKEN_SIGNATURE
INVALID_ACCESS_TOKEN_GRANTS
EXPIRATION_EXCEEDS_MAX_ALLOWED_TIME
MAX_ALLOWED_LOGIN_REACHED
onMediaPermission(event) Occurs when media permission has been granted. event returns the stream access status. The success event returns {'status':'success','stream':true}. On failure the event returns {'status':'failure','error':errorName}.
onWebrtcNotSupported Occurs when browser does not support WebRTC.
mediaMetrics Works only for Chrome. Object sent in the event callback:

high_jitter: when the jitter is higher than 30 ms for three out of last five samples. { group: ‘network’, level: ‘warning’, type: ‘high_jitter’, value: ‘<current jitter value>’, active: true || false, //Will be false when value goes to normal level. desc: ‘jitterLocalMeasures’ || ‘jitterRemoteMeasures’, stream: ‘local || remote’ }

high_rtt: When the RTT is higher than 400 ms for three out of last five samples.
{ group: ‘network’, level: ‘warning’, type: ‘high_rtt’, value: ‘<average rtt value>', active: true || false, //Will be false when value goes to normal level. desc: ‘high latency’, stream: ‘None’ }

high_packetloss: When the packet loss is > 10% for Opus and loss > 20% PCMU. { group: ‘network’, level: ‘warning’, type: ‘high_packetloss’, value: ‘<average packet loss value>';, active: true || false, //Will be false when value goes to normal level. desc: ‘packetLossLocalMeasure’ || ‘packetLossRemoteMeasure’, stream: ‘local || remote’ }

low_mos: When sampled MOS is < 3 for three out of last five samples, no_microphone_access When we detect one way audio (<80 bytes sent in three seconds). { group: ‘network’, level: ‘warning’, type: ‘low_mos’, value: ‘<current mos value>', active: true || false, //Will be false when value goes to normal level. desc: ‘mosRemoteMeasure’, stream: ‘None’ }

no_audio_received : When remote or local audio is silent. { group: ‘audio’, level: ‘warning’, type: ‘no_audio_received’, value: ‘<current audio level in dB>', active: true || false, //Will be false when value goes to normal level. desc: ‘local_audio’ || ‘remote_audio’, stream: ‘local || remote’ }

ice_timeout : Alert if ICE gathering takes more than two seconds either for outgoing call invite or incoming call answer. { group: ‘network’, level: ‘warning’, type: ‘ice_timeout’, value: ‘2000’, active: true, desc: ‘Possible NAT/Firewall issue’, stream: ‘None’ }

no_microphone_access : When Chrome losses access to microphone. This event is generated if preDetectOwa is set to true. { group: ‘audio’, level: ‘warning’, type: ‘no_microphone_access’, active: true, desc: ‘Chrome lost access to microphone — restart browser’, stream: ‘None’ }

ice_connection : When call’s ICE connection state changes. { group: ‘network’, level: ‘warning’, type: ‘ice_connection’, active: true || false, // Will be false when value is ‘connected’ value: ‘connected’ || ‘disconnected’ || ‘failed’, desc: ‘network drop’, //when value is ‘connected’ stream: ‘None’ }

mute_detection: Speech is detected when the call is muted during an ongoing conversation. { group: ‘audio’, level: ‘warning’, type: ‘speaking_on_mute’, active: true value: ‘0‘, desc: ‘User is trying to speak on mute’ stream: ‘None’ }
audioDeviceChange(deviceObj) Occurs when a USB audio device is added or removed. This event emits an object with two properties: change and device. change may have the values added or removed. device provides device-specific properties.
onConnectionChange Generated when the state of Plivo's WebSocket connection changes; for example, when the WebSocket is disconnected due to internet issues.
On WebSocket disconnect { 'state':'disconnected', 'eventCode':<code>, 'eventReason':<reason> }

On WebSocket reconnect { 'state':'connected' }

Common WebSocket event codes (RFC 6455)
1006 indicates that the connection was closed abnormally, without sending or receiving a Close control frame. For example, internet disconnection.
1009 indicates that an endpoint is terminating the connection because it has received a message that is too big for it to process.
1011 indicates that a server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.
onNoiseReductionReady Upon initialization of the SDK with the "enableNoiseReduction" flag, a necessary file for call processing is loaded. Once the file is successfully loaded and prepared for use, the "onNoiseReductionReady" event is triggered. Subsequently, you have the option to initiate noise suppression by calling the "startNoiseReduction()" function at any point.
onWebSocketConnected This event triggers when the SDK is connected to the Plivo servers.
volume(audioStats) Display user real-time volume of mic and speaker.

The volume event handler is invoked 60 times per second. The handler receives inputVolume and outputVolume as percentages of maximum volume represented by a floating point number between 0.0 and 1.0, inclusive. This value represents a range of relative decibel values between -100dB and -30dB.

audioStats JSON object: { 'inputVolume': '<relative_value_on_scale_0_to_1>', 'outputVolume': '<relative_value_on_scale_0_to_1>' }
'inputVolume': input device volume (mic)
'outputVolume': output device volume (speaker)
onDtmfReceived(dtmfData) DTMF received from the other end during an ongoing call.

dtmf data JSON object: { tone: '<dtmf_tone>', duration: '<dtmf_duration>', };
'tone': dtmf tone received from other end
'duration': duration of the tone received

CallInfo object

A CallInfo object is passed as a parameter for the following event callbacks:

1. onCallRemoteRinging
2. onCallConnected
3. onCallAnswered
4. onMediaConnected
5. onCallTerminated
6. onIncomingCall
7. onIncomingCallCanceled
8. onIncomingCallIgnored
9. onCallFailed
This JSON object contains the callUUID as well as other information about the call for which the event was generated.

Property Description
callUUID The UUID of the call.
direction The call direction. Can be INCOMING or OUTGOING.
src The source address for the call.
Will be the SIP URI of the endpoint in the case of an outgoing call.
Will be the FROM number/endpoint in the case of an incoming call.
dest The destination address for the call.
Will be the TO number/endpoint in the case of an outgoing call.
Will be the the SIP URI of the endpoint in the case of an incoming call.
extraHeaders The extraHeaders (json object) sent to or received from the Plivo SIP server.
Reason Indicates the cause of disconnection.
Protocol The values can be either Q.850 or SIP.
Code Hangup error code from SIP.
Originator Source of disconnection, with possible values being remote or local.
state The current state of the call.
Can be one of:
1. ringing
2. answered
3. rejected
4. ignored
5. canceled
6. failed
7. ended
Call state will be set to failed if an error leads to the call being hung up before it could be answered.

Examples

Visit our GitHub repo for examples.