function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Emilien Guichard 40Emilien Guichard 40 

Module Build an Instant Notification App - No bear notification received

Hello,

I am currently going though the trailhead module Build an Instant Notification App at the step Subscribe to a Platform Event

I have Verified this step but when I click Broadcast bear warning button, nothing is diplayed in my Salesforce org.
I have tried to refresh the page and even to clear the cache.

Here is my code :
NotificationConsole.cmp
<aura:component controller="NotificationController" implements="flexipage:availableForAllPageTypes" access="global">
		
    <ltng:require scripts="{!$Resource.cometd}" afterScriptsLoaded="{!c.onCometdLoaded}"/>
    
    <aura:attribute name="sessionId" type="String"/>
    <aura:attribute name="cometd" type="Object"/>
    <aura:attribute name="cometdSubscriptions" type="Object[]"/>
    
  <aura:attribute name="notifications" type="Object[]"/>
  <aura:attribute name="isMuted" type="Boolean" default="false"/>

  <aura:handler name="init" value="{!this}" action="{!c.onInit}"/>

  <aura:registerEvent name="toastEvent" type="force:showToast"/>


  <div class="container">

    <!-- Header -->
    <div class="slds-p-around--x-small slds-border--bottom slds-theme--shade">
      <div class="slds-grid slds-grid--align-spread slds-grid--vertical-align-center">
        <div>
          <span class="slds-badge">{!v.notifications.length}</span>
        </div>
        <div>
          <lightning:buttonIcon onclick="{!c.onClear}" iconName="utility:delete" title="Clear notifications"
            alternativeText="Clear notifications" variant="border-filled"/>
          <lightning:buttonIcon onclick="{!c.onToggleMute}"
            iconName="{!v.isMuted ? 'utility:volume_off' : 'utility:volume_high'}"
            title="{!v.isMuted ? 'Unmute notifications' : 'Mute notifications'}"
            alternativeText="Toggle mute" variant="border-filled"/>
        </div>
      </div>
    </div>

    <!-- Notification list -->
    <div class="slds-container--fluid slds-scrollable--y content">
      <aura:iteration items="{!v.notifications}" var="notification">
        <div class="slds-p-around--small slds-border--top">
          <div class="slds-grid slds-grid--align-spread slds-has-flexi-truncate">
            <p>{!notification.message}</p>
            <p class="slds-text-color--weak slds-p-left--x-small">{!notification.time}</p>
          </div>
        </div>
      </aura:iteration>
    </div>

  </div>

</aura:component>

NotificationConsoleController.js
({
  
  onCometdLoaded : function(component, event, helper) {
  var cometd = new org.cometd.CometD();
  component.set('v.cometd', cometd);
  if (component.get('v.sessionId') != null)
    helper.connectCometd(component);
},  
    
  onInit : function(component, event, helper) {
  component.set('v.cometdSubscriptions', []);
  component.set('v.notifications', []);

  // Disconnect CometD when leaving page
  window.addEventListener('unload', function(event) {
    helper.disconnectCometd(component);
  });

  // Retrieve session id
  var action = component.get('c.getSessionId');
  action.setCallback(this, function(response) {
    if (component.isValid() && response.getState() === 'SUCCESS') {
      component.set('v.sessionId', response.getReturnValue());
      if (component.get('v.cometd') != null)
        helper.connectCometd(component);
    }
    else
      console.error(response);
  });
  $A.enqueueAction(action);

  helper.displayToast(component, 'success', 'Ready to receive notifications.');
},
    
  onClear : function(component, event, helper) {
    component.set('v.notifications', []);
    },

  onToggleMute : function(component, event, helper) {
    var isMuted = component.get('v.isMuted');
    component.set('v.isMuted', !isMuted);
    helper.displayToast(component, 'success', 'Notifications '+ ((!isMuted) ? 'muted' : 'unmuted') +'.');
    }
})

notificationConsoleHelper.js
({
  connectCometd : function(component) {
    var helper = this;

    // Configure CometD
    var cometdUrl = window.location.protocol+'//'+window.location.hostname+'/cometd/40.0/';
    var cometd = component.get('v.cometd');
    cometd.configure({
      url: cometdUrl,
      requestHeaders: { Authorization: 'OAuth '+ component.get('v.sessionId')},
      appendMessageTypeToURL : false
    });
    cometd.websocketEnabled = false;

    // Establish CometD connection
    console.log('Connecting to CometD: '+ cometdUrl);
    cometd.handshake(function(handshakeReply) {
      if (handshakeReply.successful) {
        console.log('Connected to CometD.');
        // Subscribe to platform event
        var newSubscription = cometd.subscribe('/event/Notification__e',
          function(platformEvent) {
            console.log('Platform event received: '+ JSON.stringify(platformEvent));
            helper.onReceiveNotification(component, platformEvent);
          }
        );
        // Save subscription for later
        var subscriptions = component.get('v.cometdSubscriptions');
        subscriptions.push(newSubscription);
        component.set('v.cometdSubscriptions', subscriptions);
      }
      else
        console.error('Failed to connected to CometD.');
    });
      },

  disconnectCometd : function(component) {
    var cometd = component.get('v.cometd');

    // Unsuscribe all CometD subscriptions
    cometd.batch(function() {
      var subscriptions = component.get('v.cometdSubscriptions');
      subscriptions.forEach(function (subscription) {
        cometd.unsubscribe(subscription);
      });
    });
    component.set('v.cometdSubscriptions', []);

    // Disconnect CometD
    cometd.disconnect();
    console.log('CometD disconnected.');
  },

  onReceiveNotification : function(component, platformEvent) {
    var helper = this;
    // Extract notification from platform event
    var newNotification = {
      time : $A.localizationService.formatDateTime(
        platformEvent.data.payload.CreatedDate, 'HH:mm'),
      message : platformEvent.data.payload.Message__c
    };
    // Save notification in history
    var notifications = component.get('v.notifications');
    notifications.push(newNotification);
    component.set('v.notifications', notifications);
    // Display notification in a toast if not muted
    if (!component.get('v.isMuted'))
      helper.displayToast(component, 'info', newNotification.message);
  },

  displayToast : function(component, type, message) {
    var toastEvent = $A.get('e.force:showToast');
    toastEvent.setParams({
      type: type,
      message: message
    });
    toastEvent.fire();
  }
})

Could you please advise ? This is a very nice feature and would very much like to have working.
Thanks for your help.
 
Best Answer chosen by Emilien Guichard 40
Emilien Guichard 40Emilien Guichard 40
I got to check the "run in background" checkbox on the component in the utility bar.
It is now working like a charm.

All Answers

Emilien Guichard 40Emilien Guichard 40
For the step Publish a Platform Event I also Verified correctly but no motification is displayed.
Emilien Guichard 40Emilien Guichard 40
I got to check the "run in background" checkbox on the component in the utility bar.
It is now working like a charm.
This was selected as the best answer
Roshnit KaurRoshnit Kaur
I am still facing the exact same issue even after i have the run in background flag checked as well. Still i am unable to see the notifications when i click on Broadcast Bear Warning. Can you please help?
Dan Harrison 17Dan Harrison 17
I have also had sporatic success.  I dropped off the VPN and switched browsers and still seem to have messages only occasionally get displayed.  (Yes, run in background is checked)