Browser SDK V2.1 (Beta)

Plivo BrowserSDK 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. Currently we support Google Chrome 55 and above and Firefox 51 and above.

New in Browser SDK 2.1 (Beta)

  • 1. Multiple Incoming Calls: Users are notified of all incoming calls and have the option to answer, reject or ignore any of the calls. If an incoming call is answered, the in-progress call is hung up, and other ringing calls (if any) are automatically rejected. You will have to set this parameter to 'True' to activate this feature. Otherwise, it will continue to be in the default state of 'False'. Learn more


  • 2. Ignore Incoming Calls The new Ignore (callUUID) function, when invoked on a ringing call, will stop the incoming sound (ring) and sets the local call state to 'Ignore'. The hangup message is not sent to the caller and the call keeps ringing for the caller until the call times out. Learn more


  • 3. CallInfo Object A CallInfo JSON object is now passed with all call state change events. This object contains the following information about the call for which the event was fired:

    • - callUUID

    • - direction

    • - src
    • - destination (To)

    • - extraHeaders

    • - state

Learn more

Try out the demo here:

Get started with examples

Including the javascript

Include the plivo javascript file as shown below

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

Initializing the plivoBrowserSdk Object

The plivoBrowserSdk object needs to be initialized.

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

More explanation on the ‘options’ Refer: Configuration.

Event registration

Pass function references to the events produced from the sdk. This is where your UI manipulation should handle all the different 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('onIncomingCallCanceled', onIncomingCallCanceled);
    plivoBrowserSdk.client.on('onCallFailed', onCallFailed);
    plivoBrowserSdk.client.on('onCallAnswered', onCallAnswered);
    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);
        

Registering using your Plivo Endpoint

Register using your Plivo Endpoint credentials

var username = 'johndoe12345';
var pass = 'XXXXXXXX';
plivoBrowserSdk.client.login(username, password);

Making a call

Making a call to any number/sip endpoint. Do remember that the application attached to the registered endpoint should have an answer url that will ensure that the correct <Dial> element is returned.

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 once the onIncomingCall event is received

plivoBrowserSdk.client.answer(callUUID)

callUUID is passed in the onIncomingCall event callback, this is described later in this document.

Sending DTMF

The snippet below shows how you can send a DTMF tone when in a phone call

plivoBrowserSdk.client.sendDtmf("1");

SDK Reference

Configuration Parameters

The following are the 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
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
dscp Set to true if you want 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 rejected 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.

Incoming calls are silently rejected if another call is ringing.

true/false false
clientRegion Initialisation options to set and route calls to specific MediaServer POPs ["usa_west", "usa_east", "australia", "europe", "asia", "south_america"]

Methods & Variable

These are the methods supported on plivoBrowserSdk.client

Method Description
login(username, password) Registering a Plivo endpoint
logout() Logging 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.
Example of 'extraHeaders': {'X-PH-Test1': 'test1', 'X-PH-Test2': 'test2'}
answer(callUUID) 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 or invalid callUUID is given, the SDK will attempt to answer the most recent ringing call.
hangup() Hangup the ongoing call.
reject(callUUID) Reject an incoming call.
When callUUID is given, the SDK will attempt to reject the ringing call identified by it. When callUUID is not given or invalid callUUID is given, the SDK will attempt to answer the most recent ringing call.
ignore(callUUID) Invoking this function will stop the incoming sound (ring) and set the call state to ignored, but will not send a hangup message to the dialing party. The incoming call will keep ringing for the callee until the call times out.
When callUUID is given, the SDK will attempt to ignore the incoming call identified by it. When callUUID is not given or invalid callUUID is given, the SDK will attempt to ignore the most recent ringing call.
sendDtmf(digit) Send the digits as dtmf 'digit' can be any of the following one character strings: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "*", "#"
mute() Mute the mic
unmute() Unmute the mic
setRingTone(url or boolean) Use this function to configure the ringtone played locally by the browser for incoming calls.
true (default) - default tone here will be played during incoming call
false - will not play any ringtone
url - media url which is passed will be 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 here will be played when an outbound call begins ringing. Note that ringtone and pre-answer announcements passed by Plivo’s media servers will not be played.
false - will play ringtone and pre-answer announcements received from Plivo’s media servers
url - remote ringtone is paused and media url which is passed will be played during outbound call ringing status.
setConnectTone(boolean) true (default) - Dial tone will play while the call is being connected.
false - Dial tone will not be played.
setDebug(debug) Set the log level of the sdk. Allowed values are OFF, ERROR, WARN, INFO, DEBUG, ALL
getPeerConnection() Returns an object which contains RTCPeerConnection object.
Ex: { status: ’success’, pc: RTCPeerConnection }
sendQualityFeedback(callUUID, score, comment) Send call quality feedback at the end of a call.
callUUID can be acquired through getCallUUID() for current call and getLastCallUUID() for last call.
'score' can take an integer value between 1 to 5.
Comment must be one of the following values: ['bad-audio', 'call-dropped', 'wrong-callerid', 'post-dial-delay', 'dtmf-not-captured', 'audio-latency', 'unsolicited-call', 'one-way-audio', 'no-audio', 'never-connected'].
This feedback would be sent only if 'enableTracking' flag is set to true.
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 in the cases if you want to send feedback for the last call.
webRTC() Returns true if webRTC is supported and false if there is no webrtc support
version It is a variable that returns current version of the Plivo SDK
isLoggedIn It is a variable that returns 'true' if the user is logged in and 'false' otherwise

Methods in Audio Device API plivoBrowserSdk.client.audio are as follows:

Method Description
availableDevices(filter) Returns promise which resolves with a 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.
This is a wrapper for MediaDevices.enumurateDevices() but filters out the non audio devices.
Note :
1. When media permission is not given by users labels do not appear. In this case, to get labels for device use revealAudioDevices() and 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 down devices IDs and labels - enumerateDevices
revealAudioDevices(arg) Returns a promise which resolves with ‘success’ message 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 plivoBrowserSdk.client.audio are as follows:

Object Methods and Parameters Description
microphoneDevices set(deviceID)
get()
reset()
media(source)
set method will set the audioDevice ID as default Speaker device for DTMF and remote audio. The deviceID parameter is mandatory and takes a String value.
get method will return the Speaker device ID which is set already.
reset method will remove any Speaker device ID which is already set.
mediawill take 'dtmf' or 'ringback' as source parameter and will return the corresponding HTML audio element. This parameter is mandatory.
speakerDevices set(deviceId)
get()
reset()
media(source)
set method will set the audioDevice ID as default Speaker device for DTMF and remote audio. The deviceID parameter is mandatory and takes a String value.
get method will return the Speaker device ID which is set already.
reset method will remove any Speaker device ID which is already set.
media will take 'dtmf' or 'ringback' as source parameter and will return the corresponding HTML audio element. This parameter is mandatory.
ringtoneDevices set(deviceId)
get()
reset()
media(source)
set method will set the audioDevice ID as default Speaker device for DTMF and remote audio. The deviceID parameter is mandatory and takes a String value.
get method will return the Speaker device ID which is set already.
reset method will remove any Speaker device ID which is already set.
media will take 'dtmf' or 'ringback' as source parameter and will return the corresponding HTML audio element. This parameter is mandatory.

Events

plivoBrowserSdk object emits the following 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 remote end starts ringing during an outbound call
onCallAnswered(callInfo) Occurs when an outbound call is answered
onCallTerminated(callInfo) Occurs when an outbound call has ended
onIncomingCall(callerID, extraHeaders, callInfo) Occurs when there is an incoming call. callerID provides the callerID 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 call fails. cause returns the reason for call failing.
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 3 out of last 5 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’
}


high_rtt: When the RTT is higher than 400 ms for 3 out of last 5 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’ }

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&gt>';, active: true/false, - Will be false when value goes to normal level. desc: ‘packetLossLocalMeasure’ || ‘packetLossRemoteMeasure’ }

low_mos: When sampled mos is < 3 for 3 out of last 5 samples, no_microphone_access When we detect one way audio (<80 bytes sent in 3 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’, }

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’, }

ice_timeout : Alert if ICE gathering takes more than 2 sec 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’, }

no_microphone_acesss : When chrome losses access to microphone. This event is generated if preDetectOwa is set to true. { group: ‘audio’, level: ‘warning’, type: ‘no_microphone_acesss’, active: true, dec: ‘Chrome lost access to microphone - restart browser’, }

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’, dec: ‘network drop’ - when value is ‘connected’, }
onAudioDeviceChange(deviceObj) Occurs when there is a change in USB audio device, Device added or removed. This event will emit an object with two properties "change" and "device". change will have values "added" or "removed". Device provides device specific properties
onConnectionChange This event is 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, e.g., 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.

CallInfo Object

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

1. onCallRemoteRinging
2. onCallAnswered
3. onCallTerminated
4. onIncomingCall
5. onIncomingCallCanceled
6. onIncomingCallIgnored
7. 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 one of INCOMING or OUTGOING.
src The source address for the call.
Will be the SIP URI of the endpoint in case of outgoing call.
Will be the FROM number/adpoint in case of incoming call.
dest The destination address for the call.
Will be the TO number/endpoint in case of outgoing call.
Will be the the SIP URI of the endpoint in case of incoming call.
extraHeaders The extraHeaders (json object) sent to or received from the Plivo SIP server.
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 in case of error scenarios leading to the call getting hung up before it could be answered.

Examples

Checkout our github repo for examples