Browser SDK V2.1

    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 & above,
    • Firefox 51 & above, and
    • Microsoft Edge 79 & above.

    New in Browser SDK 2.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 or ignored depending on the option passed to answer function. 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

    • 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

    • 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/plivo.min.js"/> 

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

    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('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);
        

    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");

    Configuration Parameters

    The following are the configuration parameters:

    AttributeDescriptionAllowed ValuesDefault Value
    debugEnable debug message in JS logOFF, ERROR, WARN, INFO, DEBUG, ALLINFO
    permOnClickSet to true if you want to ask for mic permission just before call connection. Otherwise it will be asked only on page load.true/falsefalse
    audioConstraintsAudio constraints object that will be passed to webRTC getUserMedia().Audio constraints values are browser specific. Refer: MediaTrackConstraints{}
    enableTrackingSet to true if you want to get mediaMetrics events and enable call quality tracking.true/falsetrue
    closeProtectionSet to true if you want to get a dialog prompt while closing the app when the call is in-progress(ringing state or answered state).true/falsefalse
    dscpSet 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/falsetrue
    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.

    Incoming calls are silently rejected if another call is ringing.

    true/falsefalse
    clientRegionInitialisation options to set and route calls to specific MediaServer POPs["usa_west", "usa_east", "australia", "europe", "asia", "south_america"]
    maxAverageBitrate

    This param may be 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 the audio is compressed to a greater extent to reduce bandwidth consumption.

    This param only applies to calls using Opus codec. Check out RFC-7587 section 7.1 for more info.

    8000 - 4800048000

    Methods & Variables

    These are the methods supported on plivoBrowserSdk.client

    MethodDescription
    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, 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 are,
    1) reject - This is the default value. The other incoming calls (if any) will be rejected.
    2) ignored - The other incoming calls (if any) will stop ringing locally but will be ringing for the caller. These incoming calls cannot be answered after ignored.
    3) letring - The other incoming calls will be ringing silently in local and will continue to ring for the caller. These incoming calls can be answered until it stops ringing.
    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 }
    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 and optional for a score of 5.
    issues - is an Array and must have at least one of the following reasons listed below for 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 users remarks.
    sendConsoleLogs - is an boolean optional paramter with default value false. Set this to true to enable Plivo's team to collect and analyze WebSDK's logs for better understand of 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 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
    versionIt is a variable that returns current version of the Plivo SDK
    isLoggedInIt 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:

    MethodDescription
    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:

    ObjectMethods and ParametersDescription
    microphoneDevices

    set(deviceID)

    get()

    reset()

    set method 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 method will return the input audio device ID which is set already.

    reset method will remove any input audio device ID which is already set.

    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 a source parameter and will return the corresponding HTML audio element. This parameter is mandatory.

    ringtoneDevices

    set(deviceID)

    get()

    reset()

    media

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

    get method will return the ringtone device ID which is set already.

    reset method will remove any ringtone device ID which is already set.

    media will return the HTML audio element for playing the ringtone.

    Events

    plivoBrowserSdk object emits the following events

    EventDescription
    onLoginOccurs when a login is successful
    onLoginFailed(cause)Occurs when a login has failed.cause returns the login failure reason
    onLogoutOccurs when a logout is successful
    onCallingOccurs when a call is initiated
    onCallRemoteRinging(callInfo)Occurs when the remote end starts ringing during an outbound call
    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
    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 or an inbound 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}
    onWebrtcNotSupportedOccurs when browser does not support WebRTC
    mediaMetricsWorks 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’, stream: ‘local || remote’ }

    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’, 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&gt>';, 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 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’, 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 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’, stream: ‘None’ }

    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’, 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’, dec: ‘network drop’ - when value is ‘connected’, stream: ‘None’ }
    audioDeviceChange(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.
    onConnectionChangeThis 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.
    volume(audioStats)Display user real-time volume of mic and speaker.

    ‘volume’ event handler will be 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 i.e mic
    'outputVolume' : output device volume i.e. speaker

    CallInfo Object

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

    1. onCallRemoteRinging
    2. onCallAnswered
    3. onMediaConnected
    4. onCallTerminated
    5. onIncomingCall
    6. onIncomingCallCanceled
    7. onIncomingCallIgnored
    8. onCallFailed

    This JSON object contains the callUUID as well as other information about the call for which the event was generated.

    PropertyDescription
    callUUIDThe UUID of the call.
    directionThe call direction. Can be one of INCOMING or OUTGOING.
    srcThe 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.
    destThe 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.
    extraHeadersThe extraHeaders (json object) sent to or received from the Plivo SIP server.
    stateThe 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