Newer Version Available

This content describes an older version of this product. View Latest

Replay Events Sample: Code Walkthrough

Learn how to register and use the CometD replay extension in JavaScript.

JavaScript Sample for Replaying Events

The Visualforce components in the durable streaming sample implement a CometD client that subscribes with replay options. The components are embedded in Visualforce pages.

If you want to implement a CometD client with replay options, you can reuse the Visualforce components or adapt the JavaScript code for your app. Portions of the sample component are highlighted in this section.

The first step is to register the Salesforce-provided CometD extension cometdReplayExtension to replay events. This snippet also sets the streaming channel and the replay option. The first argument in registerExtension is an arbitrary name, which you use to unregister the extension.

1// Register Generic Streaming Replay extension
2var replayExtension = new cometdReplayExtension();
3replayExtension.setChannel(<Streaming Channel to Subscribe to>);
4replayExtension.setReplay(<Event Replay Option>);
5cometd.registerExtension('myReplayExtensionName', replayExtension);

Next, the client connects to the CometD replay endpoint. The API version in the endpoint must be 37.0 or later. The session ID value of the current session is passed in the Authorization header. The client calls the cometd configure() function to set up the connection and specify the endpoint and authorization header. Next, the client performs a handshake by calling cometd handshake() function.

1// Connect to the CometD endpoint
2cometd.configure({
3    url: window.location.protocol+'//'+window.location.hostname+ 
4        (null != window.location.port ? (':'+window.location.port) : '') +
5        '/cometd/37.0/',
6    requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}
7});
8cometd.handshake();

To ensure that every step in the connection process is successful before moving on to the next step, the client uses listeners. For example, a listener for the /meta/handshake channel checks whether the handshake is successful. If it is successful, the subscribe() function is called.

1if(!metaHandshakeListener) {
2    metaHandshakeListener = cometd.addListener('/meta/handshake', function(message) {
3        if (message.successful) {
4             $('#content').append('<br><br> DEBUG: Handshake Successful: '+
5                 JSON.stringify(message)+' <br><br>');
6                    
7             if (message.ext && message.ext[REPLAY_FROM_KEY] == true) {
8                 isExtensionEnabled = true;
9             }                    
10             subscribedToChannel = subscribe(channel);
11        } else
12             $('#content').append('DEBUG: Handshake Unsuccessful: '+
13                 JSON.stringify(message)+' <br><br>');
14    });
15}

The last step is to specify a callback for the CometD subscribe() function. CometD calls this callback function when a message is received in the channel. In this sample, the callback function displays the message data to the page. It appends the data to the div HTML element whose ID value is "content".

1function subscribe(channel) {
2    // Subscribe to a topic. 
3        // JSON-encoded update will be returned in the callback.
4    return cometd.subscribe(channel, function(message) {
5        var div = document.getElementById('content');
6        div.innerHTML = div.innerHTML + '<p>Notification ' +
7        'on channel: ' + JSON.stringify(message.channel) + '<br>' +
8        'Payload: ' + JSON.stringify(message.data.payload) + '<br>' + 
9        'Replay Id: ' + JSON.stringify(message.data.event.replayId) + '<br>' + 
10        'Full message: ' + JSON.stringify(message) + '</p><br>';
11    });
12}

cometdReplayExtension Extension

The extension is a prerequisite for the replay functionality in a CometD client. In the durable streaming sample, the Visualforce components register and use the extension. If you implement a CometD client, include the replay extension in your project, but you don’t have to modify it.

Note

The cometdReplayExtension contains cometd extension functions that are called for incoming and outgoing messages. These extension functions implement the logic that checks for the extension’s registration on handshake and sets the replay option on subscription.

​On handshake, the function for incoming messages checks whether the replay extension has been registered. If so, it sets the _extensionEnabled variable to true. This function also saves the replay ID of the received message so that it can be used when a client reconnects after a timeout.

1this.incoming = function(message) {
2    if (message.channel === '/meta/handshake') {
3        if (message.ext && message.ext[REPLAY_FROM_KEY] == true) {
4            _extensionEnabled = true;
5        } else if (message.channel === _channel && message.data && message.data.event && 
6                   message.data.event.replayId) {
7            _replay = message.data.event.replayId;
8        }
9    }
10}

​On subscription, the function for outgoing messages checks whether the replay extension has been registered by inspecting the _extensionEnabled variable. If the extension is registered, the function subscribes to events based on the specified replay option. The sample sets the replay option by calling the extension’s setReplay() function.

1this.outgoing = function(message) {
2    if (message.channel === '/meta/subscribe') {
3        if (_extensionEnabled) {
4            if (!message.ext) { 
5                message.ext = {};
6            }
7            var replayFromMap = {};
8            replayFromMap[_channel] = _replay;
9            // add "ext : { "replay" : { CHANNEL : REPLAY_VALUE }}" 
10            //   to subscribe message.
11            message.ext[REPLAY_FROM_KEY] = replayFromMap;
12        }
13    }
14};