### Install and Run Demo App Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/react-demo-app/README.md Navigate to the demo app directory, install dependencies, and start the development server. ```bash cd react-demo-app npm install npm run dev ``` -------------------------------- ### Basic SdkMedia Usage Example Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Demonstrates fetching media state, requesting permissions, starting media, and accepting a session using the SDK. It shows how to handle permission denials and use device IDs. ```typescript import { ISdkMediaState, SdkMediaStateWithType } from 'genesys-cloud-webrtc-sdk'; /* async function for demonstration */ async function run () { /* fetch the beginning media state sync synchronously, then update it in the `on('state')` listener */ let mediaState: ISdkMediaState = sdk.media.getState(); sdk.media.on('state', (state: SdkMediaStateWithType) => { // emits every time devices or permissions change // this value can always be synchronously attained // using `sdk.media.getState()` mediaState = state; }); /* request permissions for the desired media types */ try { await sdkMedia.requestMediaPermissions('audio'); } catch (e) { // error getting permissions. this usually means the user denied permissions // to verify, you can check the error type or check the mediaState (preferred) const { hasMicPermissions } = sdk.media.getState(); // get the current media state if (!hasMicPermissions) { // decide what to do. the sdk cannot function // without media permissions. generally it is best // to kick the user out of the app and explain how they // can grant permissions for their specific browser } } /* if we get here, that means we have `audio` permissions and devices have been enumerated */ const devices = mediaState.devices; const audioDevices = mediaState.audioDevices; // or just grab microphones /* you can request media through the sdk. if there are permissions issues, the state will be updated */ const micId = audioDevices[0].deviceId; const audioStream = await sdk.media.startMedia({ audio: micId }); /* this is a mock session object. the real session would be attained through the `sdk.on('sessionStarted', evt)` listener */ const sessionToAccept = { conversationId: 'some-hash-id', ...restOfSessionObject }; /* you can even accept a pending session with media you already have */ sdk.acceptSession({ conversationId: sessionToAccept.conversationid, mediaStream: audioStream }); /* OR you can even accept a pending session with a deviceId and the sdk will create the media */ sdk.acceptSession({ conversationId: sessionToAccept.conversationid, audioDeviceId: micId, }); } run(); ``` -------------------------------- ### Development Setup for Genesys Cloud WebRTC SDK Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/README.md Install project dependencies and run tests in watch mode for active development. Ensure all linting and tests pass with 100% coverage. ```sh npm install npm run test:watch ``` -------------------------------- ### Install Genesys Cloud WebRTC SDK Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/README.md Use npm or yarn to install the SDK. This is the first step before integrating WebRTC features. ```sh # npm npm install --save genesys-cloud-webrtc-sdk ``` ```sh # yarn yarn add genesys-cloud-webrtc-sdk ``` -------------------------------- ### Request Audio Permissions Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Request audio permissions, ensuring they are granted before starting media. This example demonstrates requesting only audio permissions and ignoring video options. ```typescript await requestMediaPermissions( 'audio', false, { audio: false, video: 'some-video-device-id', videoFrameRate: 30 } ); // since type === 'audio', the options will be converted to: { // a valid option must be set (`false|undefined` are invalid) audio: true, // video will be ignored since permissions are requested one at a time video: false } ``` -------------------------------- ### startScreenShare() Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Starts a screen share session. Currently only supported for guest users. Requires `initialize()` to be called first. ```APIDOC ## startScreenShare() ### Description Starts a screen share. Currently, screen share is only supported for guest users. `initialize()` must be called first. ### Declaration ```typescript startScreenShare(): Promise; ``` ### Returns `MediaStream` promise for the selected screen stream. ``` -------------------------------- ### Build SDK and Run Demo App Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/react-demo-app/README.md If you have made local changes to the SDK, build the SDK first, then install demo app dependencies and run the development server. ```bash # SDK npm run build # Demo app cd react-demo-app npm install npm run dev ``` -------------------------------- ### Start Screen Share Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Begins a screen sharing session, currently supported only for guest users. `initialize()` must be called first. ```typescript startScreenShare(): Promise; ``` -------------------------------- ### Start Screen Share Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/video.md Initiates the screen sharing process, prompting the user to select a screen to share. ```APIDOC ## startScreenShare() ### Description Prompts the user to select a screen to share with other participants. This method will throw an error if the user cancels the screen selection prompt. > Note: Screen sharing is not supported concurrently with camera video. If camera video is active, it will be replaced by the screen share track. Upon ending screen share, camera video will be re-established if it was previously active. ### Method `session.startScreenShare(): Promise;` ### Parameters None ### Returns A promise that resolves when the screen share has successfully started. ``` -------------------------------- ### CDN Installation Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Instructions for including the WebRTC SDK in your project using a CDN, with options for the latest major version or a specific version. ```APIDOC ## CDN Installation Include the SDK via CDN for direct browser usage. ```html ``` ``` -------------------------------- ### Import and Initialize GenesysCloudWebrtcSdk Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Import the extended media session interface and the SDK. Initialize the SDK with configuration options and set up an event listener for session started events to capture the active session. ```typescript import { IExtendedMediaSession, GenesysCloudWebrtcSdk, } from 'genesys-cloud-webrtc-sdk'; const sdk = new GenesysCloudWebrtcSdk({ /* your config options */ }); let activeSession: IExtendedMediaSession; sdk.on('sessionStarted', (session) => { activeSession = session; // `session` is already strongly typed }); ``` -------------------------------- ### Initialize SDK Script Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/test/test-pages/index-template.html Loads the Genesys Cloud WebRTC SDK from a CDN or local path. This script setup is necessary before initializing the SDK. ```javascript if (window.location.href.indexOf('/cdn') > -1) { const script = document.createElement('script'); // for local development // script.src = '../../dist/genesys-cloud-webrtc-sdk.js'; script.src = 'https://sdk-cdn.mypurecloud.com/webrtc-sdk/v7/genesys-cloud-webrtc-sdk.js'; document.head.prepend(script); } ``` -------------------------------- ### Listen for Session Started Events Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Fired when the negotiation for a session has started, prior to the session connecting. It provides the extended media session object. ```typescript sdk.on('sessionStarted', (session: IExtendedMediaSession) => {}); ``` -------------------------------- ### Start Video Conference Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/video.md Initiates a video conference by providing the room JID. Ensure you have set up necessary event listeners before calling this method. ```APIDOC ## startVideoConference(roomJid) ### Description Starts a video conference in the specified room. ### Method `sdk.startVideoConference(roomJid)` ### Parameters #### Path Parameters - **roomJid** (string) - Required - The JID of the room to join. ### Request Example ```ts await sdk.startVideoConference("your-room-jid"); ``` ``` -------------------------------- ### Target Role: Accept Session with Screen Media Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/live-screen-monitoring.md Example of how the target role accepts a live screen monitoring session by providing the required screen media stream and metadata. ```typescript // Target accepts with screen media sdk.acceptSession({ conversationId: session.conversationId, sessionType: session.sessionType, mediaStream: screenStream, // Required for targets liveScreenMonitoringMetadata }); ``` -------------------------------- ### Start Softphone Session Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Initiates a softphone call session. Ensure `initialize()` has been called prior to using this method. ```typescript startSoftphoneSession(softphoneSessionParams: IStartSoftphoneSessionParams): Promise<{id: string, selfUri: string}>; ``` -------------------------------- ### Start Video Meeting Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Initiates a video meeting using a provided meeting ID. Requires prior initialization of the SDK and is only supported for authenticated users within the same organization. ```typescript startVideoMeeting(meetingId: string): Promise<{ conversationId: string }>; ``` -------------------------------- ### startVideoMeeting Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Starts a video meeting using a provided meeting ID. This method requires prior initialization of the SDK and is only supported for authenticated users within the same organization. It returns the conversation ID for the newly created meeting. ```APIDOC ## startVideoMeeting(meetingId: string) ### Description Starts a video meeting with a meetingId. Not supported for guests. Meetings can only be joined by authenticated users from the same organization. `initialize()` must be called first. ### Method ```ts startVideoMeeting(meetingId: string): Promise<{ conversationId: string }> ``` ### Parameters #### Path Parameters - `meetingId` (string) - Required - meeting id for the meeting to join, generated by the Genesys Cloud Public API (functionality currently in Preview). ### Response #### Success Response (200) - `conversationId` (string) - The newly created conversation ID for the meeting. ``` -------------------------------- ### SdkHeadset Example Usage Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/headset.md Demonstrates how to use the SdkHeadset for call control actions like answering, muting, ending calls, and handling various headset events. ```APIDOC ## SdkHeadset Example Usage This section provides examples of how to interact with the SdkHeadset for call management and event handling. ### Example Usage ``` ts /* async function for demonstration */ async function testAnswerCall () { /* This function handles a fromHeadset event. This will not cause the headset library to be called */ sdk.acceptPendingSession('123456789', 'softphone', true); } async function testMuteCall () { /* This function handles a from app event. This will cause the headset library to be called */ sdk.setAudioMute ('123456789', 'softphone', false | undefined); } /* Examples of listening for events from the headset */ sdk.headset.headsetEvents.subscribe(value: { event: HeadsetEvents, payload: { name: string, event: {`object containing various items from the headset`}, isMuted: boolean, holdRequested: boolean, isConnected: boolean, isConnecting: boolean, callback: Function, toggle?: boolean, code?: string } } => { switch (value.event) { case 'deviceAnsweredCall': sdk.acceptPendingSession(); break; case 'deviceEndedCall': sdk.endSession(); break; case 'deviceMuteStatusChanged': sdk.setAudioMute(value.payload.isMuted); break; case 'deviceHoldStatusChanged': sdk.setConversationHold(value.payload.holdRequested, value.payload.toggle); break; case 'deviceRejectedCall': sdk.rejectPendingSession(value.payload.conversationId); break; case 'webHidPermissionRequested': anyNecessaryFunctions(value.payload.callback); break; case 'deviceConnectionStatusChanged': console.log({ isConnecting: value.payload.isConnecting, isConnected: value.payload.isConnected }) anyNecessaryFunctions(value.payload.isConnected, value.payload.isConnecting) break; default: // console.log('some other event'); } } ``` ``` -------------------------------- ### Start Screen Capture Stream Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Creates a media stream from the user's screen. This action will prompt the user to select which screen or window to share. Refer to browser-specific documentation for detailed permission information. ```typescript startDisplayMedia(): Promise; ``` -------------------------------- ### Access GenesysCloudWebrtcSdk via CDN Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md This example demonstrates how to include the WebRTC SDK using a CDN link, allowing access to the latest major version or a specific version. The SDK is then accessed through the `window` object. ```html ``` -------------------------------- ### Get Media State Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Retrieves a copy of the current media state of the SDK. ```typescript getState(): ISdkMediaState; ``` -------------------------------- ### Start Media Stream Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Creates a media stream with audio and/or video. It's highly recommended to call `requestMediaPermissions()` beforehand. This function handles requesting permissions if not already granted and includes retry logic for failures, especially for video resolution issues or device ID mismatches. ```typescript startMedia(mediaReqOptions?: IMediaRequestOptions, retryOnFailure?: boolean): Promise; ``` -------------------------------- ### Start and Accept Video Conference Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/video.md Initiates a video conference and sets up event listeners to accept the session. Ensure you have an initialized WebrtcSdk instance and provide valid HTML elements for audio and video. ```typescript sdk.on('sessionStarted', function (session) => { // accept session if (session.sessionType === 'collaborateVideo') { const audioElement = document.getElementById('vid-audio'); const videoElement = document.getElementById('vid-video'); const sessionEventsToLog = [ 'participantsUpdate', 'activeVideoParticipantsUpdate', 'speakersUpdate' ]; sessionEventsToLog.forEach((eventName) => { session.on(eventName, (e) => console.info(eventName, e)); }); sdk.acceptSession({ conversationId: session.conversationId, audioElement, videoElement }); } }); await sdk.startVideoConference(roomJid); ``` -------------------------------- ### Start a Softphone Session Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/softphone.md Initiates a new softphone call to a specified phone number. Ensure the SDK is initialized and events are set up before calling this method. ```typescript await sdk.startSoftphoneSession({phoneNumber: '15555555555'}); ``` -------------------------------- ### Start Video Conference Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Initiates a video conference. This feature is not available for guests and requires authenticated users from the same organization. An optional `inviteeJid` can be provided to invite a specific user. ```typescript startVideoConference(roomJid: string, inviteeJid?: string): Promise<{ conversationId: string; }>; ``` -------------------------------- ### Define Allowed Session Types for SDK Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Specify which session types the SDK instance should handle. If not provided, all session types are allowed by default. This example restricts the SDK to handle only collaborate video and softphone sessions. ```typescript import { SessionTypes } from 'genesys-cloud-webrtc-sdk'; const sdk = new GenesysCloudWebrtcSdk({ allowedSessionTypes: [SessionTypes.collaborateVideo, SessionTypes.softphone], // other config options }); ``` -------------------------------- ### Start Screen Sharing in Video Session Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/video.md Initiates screen sharing within a video conference. This action will replace the camera video track with the screen share track. It prompts the user for screen selection and may throw an error if the user cancels. ```typescript session.startScreenShare(): Promise; ``` -------------------------------- ### Softphone Session Parameters Interface Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/softphone.md Defines the parameters for starting a softphone session, including phone number, caller ID, and routing information. Use this interface to structure the arguments for `startSoftphoneSession`. ```typescript interface IStartSoftphoneSessionParams { phoneNumber?: string; callerId?: string; callerIdName?: string; callFromQueueId?: string; callQueueId?: string; callUserId?: string; priority?: number; languageId?: string; routingSkillsIds?: string[]; conversationIds?: string[]; participants?: ISdkSoftphoneDestination[]; uuiData?: string; } ``` -------------------------------- ### jidResource Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Specify the resource portion of the streaming-client jid. This is likely only useful for internal purposes. This resource jid should be _somewhat_ unique. Example: setting the jidResource to `mediahelper_1d43c477-ab34-456b-91f5-c6a993c29f25` would result in full jid that looks like `/mediahelper_1d43c477-ab34-456b-91f5-c6a993c29f25`. The purpose of this property is simply a way to identify certain types of clients. ```APIDOC jidResource?: string; Optional: default `undefined` ``` -------------------------------- ### requestMediaPermissions Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Requests media permissions for audio, video, or both. This function should be called early in the SDK lifecycle, before starting media playback, to ensure permissions are granted by the browser and OS. It also enumerates devices and updates the media state, emitting a 'permissions' event. ```APIDOC ## requestMediaPermissions() ### Description Function to gain permissions for a given media type. This function should be called early after constructing the SDK and _before_ calling `sdk.media.startMedia()` to ensure permissions are granted. It will also call through to `sdk.media.enumerateDevices()` to ensure all devices have been loaded after permissions have been granted. The media state will be updated with permissions and an event emitted on `sdk.media.on('permissions', evt)` with any outcomes. An error will be thrown if permissions are not granted by either the browser or the OS, with specific exceptions for macOS microphone hardware mute states. If `preserveMedia` is `true`, the `MediaStream` attained through `startMedia()` will be returned; otherwise, media will be destroyed and `undefined` returned. `options` can be any valid deviceId or other media options defined in [IMediaRequestOptions]. ### Method ```ts requestMediaPermissions(mediaType: 'audio' | 'video' | 'both', preserveMedia?: boolean, options?: IMediaRequestOptions): Promise; ``` ### Parameters #### Path Parameters * `mediaType: 'audio' | 'video' | 'both'` - mediaType media type to request permissions for (`'audio' | 'video' | 'both'`) * `preserveMedia?: boolean` - Optional: Defaults to `false` – flag to return media after permissions pass * `options?: IMediaRequestOptions` - Optional: Defaults to mediaType `true`. See [IMediaRequestOptions] for additional details. See note above explaining mediaType always being requested. ### Returns a promise either containing a `MediaStream` or `undefined` depending on the value of `preserveMedia` ``` -------------------------------- ### initialize() Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Sets up the SDK and authenticates the user. Agents require an accessToken, while guests need a securityCode. ```APIDOC ## initialize() ### Description Sets up the SDK for use and authenticates the user. Agents must have an accessToken passed into the constructor options, and guests need a securityCode. ### Declaration ```typescript initialize(opts?: { securityCode: string; } | ICustomerData): Promise; ``` ### Params - `opts` = `{ securityCode: 'shortCode received from agent to share screen' }` - Or, if the customer data has already been redeemed using the securityCode (advanced usage): ```typescript interface ICustomerData { conversation: { id: string; }; sourceCommunicationId: string; jwt: string; } ``` ### Returns A Promise that is fulfilled once the web socket is connected and other necessary async tasks are complete. ``` -------------------------------- ### Basic SDK Initialization Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Demonstrates how to initialize the Genesys Cloud WebRTC SDK with an access token and set up basic event listeners. ```APIDOC ## Basic SDK Initialization This example shows how to create an instance of the WebRTC SDK for an authenticated user. ```js import { GenesysCloudWebrtcSdk } from 'genesys-cloud-webrtc-sdk'; const sdk = new GenesysCloudWebrtcSdk({ accessToken: 'your-access-token' }); // Optionally set up some SDK event listeners sdk.on('sdkError', (event) => { /* handle error */ }); sdk.on('pendingSession', (event) => { /* handle pending session */ }); sdk.on('sessionStarted', (event) => { /* handle session start */ }); sdk.initialize().then(() => { // SDK is ready }); ``` ``` -------------------------------- ### Get All Active Media Tracks Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Returns an array of all active media tracks that were created by the SDK. ```typescript getAllActiveMediaTracks(): MediaStreamTrack[]; ``` -------------------------------- ### startDisplayMedia Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Captures the user's screen content as a media stream. This action will prompt the user to select which screen or window to share. ```APIDOC ## startDisplayMedia() ### Description Creates a `MediaStream` from the user's screen, which will prompt for user screen selection. ### Method `startDisplayMedia(): Promise` ### Parameters None ### Returns A promise containing a `MediaStream` with the requested screen media. ``` -------------------------------- ### Get Cached Video Devices Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Returns an array of all video devices currently cached by the SDK. ```typescript getVideoDevices(): MediaDeviceInfo[]; ``` -------------------------------- ### Get Cached Audio Devices Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Returns an array of all audio devices currently cached by the SDK. ```typescript getAudioDevices(): MediaDeviceInfo[]; ``` -------------------------------- ### startVideoConference() Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Initiates a video conference. Not supported for guests. Requires `initialize()` to be called first. ```APIDOC ## startVideoConference() ### Description Starts a video conference. Not supported for guests. Conferences can only be joined by authenticated users from the same organization. If `inviteeJid` is provided, the specified user will receive a propose/pending session they can accept and join the conference. `initialize()` must be called first. ### Declaration ```typescript startVideoConference(roomJid: string, inviteeJid?: string): Promise<{ conversationId: string; }>; ``` ### Params - `roomJid: string` Required: jid of the conference to join. Can be made up if starting a new conference but must adhere to the format: `@conference.` - `inviteeJid?: string` Optional: jid of a user to invite to this conference. ### Returns A promise with an object with the newly created `conversationId`. ``` -------------------------------- ### Get All Cached Media Devices Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Returns an array of all media devices currently cached by the SDK. ```typescript getDevices(): MediaDeviceInfo[]; ``` -------------------------------- ### sessionState Event Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Emitted when the state of the session changes. Possible states include 'starting', 'pending', and 'active'. ```APIDOC ## sessionState Event ### Description Emitted when the state of the session changes. ### Event Name sessionState ### Parameters - **sessionState** ('starting' | 'pending' | 'active') - The new state of the session. ``` -------------------------------- ### Initialize GenesysCloudWebrtcSdk with Access Token Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md This snippet shows the basic initialization of the WebRTC SDK for an authenticated user using an access token. It also demonstrates how to set up event listeners for common SDK events and initialize the SDK. ```javascript import { GenesysCloudWebrtcSdk } from 'genesys-cloud-webrtc-sdk'; const sdk = new GenesysCloudWebrtcSdk({ accessToken: 'your-access-token' }); // Optionally set up some SDK event listeners (not an exhaustive list) sdk.on('sdkError' (event) => { /* do stuff with the error */ }); sdk.on('pendingSession' (event) => { /* pending session incoming */ }); sdk.on('sessionStarted' (event) => { /* a session just started */ }); sdk.initialize().then(() => { // the web socket has connected and the SDK is ready to use }); ``` -------------------------------- ### startMedia Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Initiates a media stream with audio and/or video. It's recommended to call `requestMediaPermissions` beforehand. Handles retries on failure and offers options to preserve media if one type fails. ```APIDOC ## startMedia() ### Description Creates a media stream with audio and/or video. It is recommended to request media permissions before calling this method. The function handles retries on failure and provides options for preserving media if one type fails. ### Method `startMedia(mediaReqOptions?: IMediaRequestOptions, retryOnFailure?: boolean): Promise` ### Parameters #### Query Parameters - **mediaReqOptions** (IMediaRequestOptions) - Optional: Defaults to `{ video: true, audio: true }` – Options for requesting video and/or audio, including device selection. See [IMediaRequestOptions] for more details. - **retryOnFailure** (boolean) - Optional: (Deprecated, use `mediaReqOptions.retryOnFailure`) Defaults to `true` – Specifies whether the SDK should retry on an error. ### Returns A promise containing a `MediaStream` with the requested media. ``` -------------------------------- ### Get Cached Output Devices Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Returns an array of all audio output devices currently cached by the SDK. ```typescript getOutputDevices(): MediaDeviceInfo[]; ``` -------------------------------- ### Listen for RTCPeerConnection State Changes Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md This event fires when the state of the underlying RTCPeerConnection changes. It provides detailed states from 'starting' to 'failed'. ```typescript session.on( 'connectionState', ( connectionState: | 'starting' | 'connecting' | 'connected' | 'interrupted' | 'disconnected' | 'failed' ) => {} ); ``` -------------------------------- ### connectionState Event Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Emitted when the state of the underlying RTCPeerConnection changes. This includes states like 'starting', 'connecting', 'connected', 'interrupted', 'disconnected', and 'failed'. ```APIDOC ## connectionState Event ### Description Emitted when the state of the underlying RTCPeerConnection state changes. ### Event Name connectionState ### Parameters - **connectionState** ('starting' | 'connecting' | 'connected' | 'interrupted' | 'disconnected' | 'failed') - The new state of the RTCPeerConnection. ``` -------------------------------- ### Listen for Session State Changes Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Use this snippet to be notified when the state of a session changes. It covers states like 'starting', 'pending', and 'active'. ```typescript session.on( 'sessionState', (sessionState: 'starting' | 'pending' | 'active') => {} ); ``` -------------------------------- ### SDK Initialization Options Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Specifies the parameters required for initializing the SDK, including security codes for guests or customer data for advanced usage. ```typescript initialize(opts?: { securityCode: string; } | ICustomerData): Promise; ``` ```typescript interface ICustomerData { conversation: { id: string; }; sourceCommunicationId: string; jwt: string; } ``` -------------------------------- ### Get ICE Connection Type Information Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Emits information about the ICE connection, including local and remote candidate types, and whether the connection is relayed. ```typescript session.on('iceConnectionType', (iceConnectionType: { localCandidateType: string, relayed: boolean, remoteCandidateType: string })) => { }); ``` -------------------------------- ### SDK Constructor and Configuration Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Details the `GenesysCloudWebrtcSdk` constructor and the `ISdkConfig` interface, outlining all available configuration options. ```APIDOC ## `constructor(config: ISdkConfig)` Initializes the WebRTC SDK with a configuration object. ### `ISdkConfig` Interface ```ts interface ISdkConfig { environment?: string; accessToken?: string; jwt?: string; organizationId?: string; wsHost?: string; autoConnectSessions?: boolean; autoAcceptPendingScreenRecordingRequests?: boolean; autoAcceptPendingLiveScreenMonitoringRequests?: boolean; jidResource?: string; disableAutoAnswer?: boolean; logLevel?: LogLevels; logger?: ILogger; logFormatters?: LogFormatterFn[]; optOutOfTelemetry?: boolean; useHeadsets?: boolean; originAppName?: string; originAppVersion?: string; originAppId?: string; allowedSessionTypes?: SessionTypes[]; defaults?: { audioStream?: MediaStream; audioElement?: HTMLAudioElement; videoElement?: HTMLVideoElement; videoResolution?: { width: ConstrainULong; height: ConstrainULong; }; videoDeviceId?: string | null; audioDeviceId?: string | null; audioVolume?: number; outputDeviceId?: string | null; micAutoGainControl?: ConstrainBoolean; micEchoCancellation?: ConstrainBoolean; micNoiseSuppression?: ConstrainBoolean; monitorMicVolume?: boolean; }; } ``` #### `environment` `environment?: string;` Domain to use. Optional: default is `mypurecloud.com`. Available Options: ```ts 'mypurecloud.com', 'mypurecloud.com.au', 'mypurecloud.jp', 'mypurecloud.de', 'mypurecloud.ie', 'usw2.pure.cloud', 'cac1.pure.cloud', 'euw2.pure.cloud', 'apne2.pure.cloud'; ``` #### `accessToken` `accessToken?: string;` Access token received from authentication. Required for authenticated users. #### `jwt` `jwt?: string;` Genesys-signed JWT for limited agent access (screen-recording, video conferencing). Cannot be used with `accessToken` or guest access. #### `organizationId` `organizationId?: string;` Organization ID (GUID). Required for unauthenticated (guest) users. #### `wsHost` `wsHost?: string;` Optional: defaults to `wss://streaming.${config.environment}` WebSocket Host. #### `autoConnectSessions` `autoConnectSessions?: boolean;` Optional: default `true` Automatically connect incoming softphone sessions. If `false`, sessions must be manually accepted using `sdk.acceptSession({ conversationId })`. #### `autoAcceptPendingScreenRecordingRequests` `autoAcceptPendingScreenRecordingRequests?: boolean;` Optional: default `false` If `true`, incoming screen recording requests are accepted immediately. The `pendingSession` event will not be emitted. The consumer must still handle the `sessionStarted` event to add screen media and call `sdk.acceptSession(...)`. ``` -------------------------------- ### Listen for Conversation Updates Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Use this event to track changes in softphone conversations, such as new conversations starting, ending, or participant states changing. This event is only for softphone conversations. ```typescript sdk.on('conversationUpdate', (event: ISdkConversationUpdateEvent) => {}); ``` -------------------------------- ### sdk.audioProcessor.init() Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/audio-processor.md Initializes the currently set audio processor. This is typically called automatically by `setAudioProcessor()` or when a processor is provided via SDK configuration. ```APIDOC ## `sdk.audioProcessor.init()` Initialize the currently set audio processor. This is called automatically by [`setAudioProcessor()`](#setaudioprocessor) and when a processor is provided via SDK config, so it generally does not need to be called directly. If no processor has been set, this logs an error and returns. Declaration: ```ts init(): Promise; ``` Returns: a promise that resolves once the processor has been initialized. ``` -------------------------------- ### Accept Live Screen Monitoring Session (Automatic) Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/live-screen-monitoring.md Automatically accepts an incoming live screen monitoring session, gathers screen media, and adds it to the session. Requires the SDK to be configured for automatic acceptance. ```typescript sdk.on('sessionStarted', async (session) => { if (sdk.isLiveScreenMonitoringSession(session)) { // gather media - the SDK does *not* gather screen media for you const screenStream = await navigator.getDisplayMedia(); // create metadata for the screen being monitored const track = screenStream.getTracks()[0]; const { height, width, deviceId } = track.getSettings(); const liveScreenMonitoringMetadata = [ { trackId: track.id, screenId: deviceId, originX: 0, originY: 0, resolutionX: width, resolutionY: height, primary: true, } ]; sdk.acceptSession({ conversationId: session.conversationId, sessionType: session.sessionType, mediaStream: screenStream, liveScreenMonitoringMetadata }); } }); ``` -------------------------------- ### Get Current URL Parameters Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/test/test-pages/index-template.html A utility function to parse and retrieve parameters from the current URL's hash fragment. This is useful for dynamic configuration or state management. ```javascript window.getCurrentUrlParams = () => { let params = null; const urlParts = window.location.href.split('#'); if (urlParts[1]) { const urlParamsArr = urlParts[1].split('&'); if (urlParamsArr.length) { params = {}; for (let i = 0; i < urlParamsArr.length; i++) { const currParam = urlParamsArr[i].split('='); const key = currParam[0]; const value = currParam[1]; params[key] = value; } } } return params; } ``` -------------------------------- ### startSoftphoneSession() Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Initiates a softphone call session with specified participants. Requires `initialize()` to be called first. ```APIDOC ## startSoftphoneSession() ### Description Starts a softphone call session with the given peer or peers. `initialize()` must be called first. ### Declaration ```typescript startSoftphoneSession(softphoneSessionParams: IStartSoftphoneSessionParams): Promise<{id: string, selfUri: string}>; ``` ### Params - `softphoneSessionParams: IStartSoftphoneSessionParams` Required: Contains participant information for placing the call. See [softphone#IStartSoftphoneSessionParams](softphone.md#istartsoftphonesessionparams) for full details on the request parameters. ### Returns A promise with an object containing the `id` and `selfUri` for the conversation. ``` -------------------------------- ### Environment Configuration Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/test/test-pages/gcba/index.html Defines the different environments for SDK authentication, including client IDs and URIs. ```javascript window.environments = { 'dca': { // clientId: '2c75d833-922b-4324-9d0e-6c20b9c714b2', // created in valve-telphony org, dca clientId: '2e10c888-5261-45b9-ac32-860a1e67eff8', uri: 'inindca.com' }, 'pca-us': { clientId: '6b9f791c-86ef-4f7a-af85-3f3520dd0975', // created in torontohackathon org uri: 'mypurecloud.com' } }; ``` -------------------------------- ### Request Media Permissions Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Requests media permissions for audio, video, or both. This should ideally be called before `startMedia()` or `enumerateDevices()` to ensure permissions are granted. If not called, `startMedia()` will attempt to request them. ```typescript sdk.media.requestMediaPermissions('audio' | 'video' | 'both') ``` -------------------------------- ### Accept Live Screen Monitoring Session (Manual) Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/live-screen-monitoring.md Manually accepts a pending live screen monitoring session after configuring the SDK to disable automatic acceptance. Gathers screen media and adds it to the session. ```typescript const sdk = new GenesysCloudWebrtcSdk({ // other config stuff ... autoAcceptPendingLiveScreenMonitoringRequests: false }); sdk.on('pendingSession', (session) => { if (session.sessionType === SessionTypes.liveScreenMonitoring) { // manually accept the pending session sdk.acceptPendingSession({ conversationId: session.conversationId, sessionType: session.sessionType }); } }); sdk.on('sessionStarted', async (session) => { if (sdk.isLiveScreenMonitoringSession(session)) { const screenStream = await navigator.getDisplayMedia(); const track = screenStream.getTracks()[0]; const { height, width, deviceId } = track.getSettings(); const liveScreenMonitoringMetadata = [ { trackId: track.id, screenId: deviceId, originX: 0, originY: 0, resolutionX: width, resolutionY: height, primary: true, } ]; sdk.acceptSession({ conversationId: session.conversationId, sessionType: session.sessionType, mediaStream: screenStream, liveScreenMonitoringMetadata }); } }); ``` -------------------------------- ### autoAcceptPendingLiveScreenMonitoringRequests Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md If true, incoming proposes for live screen monitoring sessions will be accepted immediately and no `pendingSession` event will be emitted. The consumer will still have to react to `sessionStarted` in order to add screen media and then call `sdk.acceptSession(...)`. ```APIDOC autoAcceptPendingLiveScreenMonitoringRequests?: boolean; Optional: default `false` ``` -------------------------------- ### Available Environment Options Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md This list specifies the valid string values for the `environment` configuration option when initializing the SDK. These domains correspond to different Genesys Cloud regions. ```typescript 'mypurecloud.com', 'mypurecloud.com.au', 'mypurecloud.jp', 'mypurecloud.de', 'mypurecloud.ie', 'usw2.pure.cloud', 'cac1.pure.cloud', 'euw2.pure.cloud', 'apne2.pure.cloud'; ``` -------------------------------- ### Provide Audio Processor via SDK Config Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/audio-processor.md Configure the audio processor when initializing the SDK by passing an instance of IAudioProcessor in the constructor's defaults. ```APIDOC ## Provide Audio Processor via SDK Config Pass the processor in the SDK constructor under `defaults.audioProcessor`. When provided this way, the SDK will set and initialize the processor automatically during construction. ```ts import { GenesysCloudWebrtcSdk, IAudioProcessor } from 'genesys-cloud-webrtc-sdk'; // your implementation of IAudioProcessor const audioProcessor: IAudioProcessor = new MyAudioProcessor(); const sdk = new GenesysCloudWebrtcSdk({ accessToken: 'your-access-token', defaults: { audioProcessor } }); await sdk.initialize(); ``` See [`defaults.audioProcessor`](index.md#defaults) in the main documentation for the config option. ``` -------------------------------- ### Accept Session as Observer Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/live-screen-monitoring.md Use this when accepting a session as an observer to display incoming video streams. Observers must provide video elements and set `liveMonitoringObserver: true`. ```typescript sdk.acceptSession({ conversationId: session.conversationId, sessionType: session.sessionType, liveMonitoringObserver: true, // Identifies this as observer role videoElements: [videoElement1, videoElement2], // Required for observers }); ``` -------------------------------- ### Platform Client Initialization Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/test/test-pages/gcba/index.html Obtains a reference to the platformClient object, which is necessary for interacting with the Genesys Cloud API. ```javascript // Obtain a reference to the platformClient object window.platformClient = require('platformClient'); ``` -------------------------------- ### Get Valid Device ID Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md Validates a device ID against cached media devices. It first checks the provided ID, then the SDK default, and finally the system default if necessary. Returns undefined if no valid device is found. ```typescript getValidDeviceId(kind: MediaDeviceKind, deviceId: string | boolean | null, ...sessions: IExtendedMediaSession[]): string | undefined; ``` -------------------------------- ### Accept Screen Recording Session (Manual) Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/screen-recording.md Manually accepts pending screen recording sessions. It listens for `pendingSession` events, accepts the session if it's a screen recording type, and then handles the `sessionStarted` event to gather media and accept the session with metadata. Requires `autoAcceptPendingScreenRecordingRequests` to be `true`. ```typescript const sdk = new GenesysCloudWebrtcSdk({ // other config stuff ... autoAcceptPendingScreenRecordingRequests: true }); ... sdk.on('pendingSession', (session) => { if (pendingSession.sessionType === SessionTypes.screenRecording) { sdk.acceptPendingSession({ conversationId: session.conversationId, sessionType: session.sessionType }); } }); // set up needed events sdk.on('sessionStarted', async (session) => { if (sdk.isScreenRecordingSession(session)) { // gather media in whatever way you want. The SDK does *not* gather screen media for you const screenStream = await navigator.getDisplayMedia(); // create metadatas const track = screenStream.getTracks()[0]; const { height, width, deviceId } = track.getSettings(); const screenRecordingMetadatas = [ { trackId: track.id, screenId: deviceId, // some applications give you a deviceId on the track which is uniquely tied to a specific monitor originX: 0, originY: 0, resolutionX: width, resolutionY: height, primary: true, } ]; sdk.acceptSession({ conversationId: session.conversationId, sessionType: session.sessionType, mediaStream: screenStream, screenRecordingMetadatas }); } }); ``` -------------------------------- ### Get Valid SDK Media Request Device ID Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md A helper function to ensure a valid SDK media request parameter. It returns valid inputs as is, and converts undefined or false to true to use the SDK's default device ID. ```typescript getValidSdkMediaRequestDeviceId(deviceId?: string | boolean | null): string | null | true; ``` -------------------------------- ### Accept WebRTC Session with Options Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md Accepts a WebRTC session using provided options. This method allows for specifying media streams, audio/video elements, device IDs, and screen recording metadata. ```typescript acceptSession(acceptOptions: IAcceptSessionRequest): Promise; ``` -------------------------------- ### sdk.audioProcessor.setAudioProcessor() Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/audio-processor.md Stores the provided audio processor and immediately calls its `init()` method. This method is used to set or replace the active audio processor. ```APIDOC ## `sdk.audioProcessor.setAudioProcessor()` Set the audio processor to use. This stores the processor and immediately calls its `init()`. Declaration: ```ts setAudioProcessor(audioProcessor: IAudioProcessor): void; ``` Params: - `audioProcessor: IAudioProcessor` Required: the processor implementation to use. Returns: `void` ``` -------------------------------- ### Provide Audio Processor via SDK Config Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/audio-processor.md Pass your custom audio processor implementation during SDK initialization. The SDK will automatically set up and initialize the processor. ```typescript import { GenesysCloudWebrtcSdk, IAudioProcessor } from 'genesys-cloud-webrtc-sdk'; // your implementation of IAudioProcessor const audioProcessor: IAudioProcessor = new MyAudioProcessor(); const sdk = new GenesysCloudWebrtcSdk({ accessToken: 'your-access-token', defaults: { audioProcessor } }); await sdk.initialize(); ``` -------------------------------- ### SDK Ready Event Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/index.md This event fires once after the SDK has been successfully initialized using `sdk.initialize()`. It signifies that the SDK is ready for use. ```typescript sdk.on('ready', () => {}); ``` -------------------------------- ### Environment Configuration Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/test/test-pages/index-template.html Defines different environments for SDK authentication, including client IDs and URIs. This configuration is used to connect to specific PureCloud instances. ```javascript window.environments = { 'dca': { // clientId: '2c75d833-922b-4324-9d0e-6c20b9c714b2', // created in valve-telphony org, dca clientId: '2e10c888-5261-45b9-ac32-860a1e67eff8', uri: 'inindca.com' }, 'pca-us': { clientId: '6b9f791c-86ef-4f7a-af85-3f3520dd0975', // created in torontohackathon org uri: 'mypurecloud.com' } }; ``` -------------------------------- ### Monitor getUserMedia Requests Source: https://github.com/mypurecloud/genesys-cloud-webrtc-sdk/blob/develop/doc/media.md This event fires whenever the SDK initiates a getUserMedia request. Monitor this to ensure the window is in focus for the request to succeed. ```typescript sdk.media.on('gumRequest', (request: ISdkGumRequest) => { }); ```