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
Nikhil Garg 17Nikhil Garg 17 

Subscribe platform event in vf page

Hi Team,

I got stuck in one  problem, Actuallly I need to send data from my apex class to vf page using platform events, but I'm stuck in how to subscribe my platform event in my vf page and get data.

kindly give soultion for the same.
Sukanya BanekarSukanya Banekar
Hi Nikhil,

Can you please elaboarte more about this use case. Till then sharing a code snippet which might help you.
You need to insert platform Event record in apex class:
PlatformEvent__e event = new PlatformEvent__e();
event.Field1__c = 'somevalue';
And you can subscribe the event in vf page:
<apex:page >
 <apex:includeScript value="{!$Resource.cometd"/> 
<apex:includeScript value="{!$Resource.jquery}"/> 
<apex:includeScript value="{!$Resource.json2}"/> 
<apex:includeScript value="{!$Resource.jquery_cometd}"/> 
         $cometd.configure({ url: 'https://<Salesforce_URL>/cometd/41.0/', 
                    requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'} 

        $.cometd.subscribe('/event/Apinameof event', function(message){   
         //logic - whenever event gets fired. 


You can get the static resource for cometd from the link below:

Let me know if this helps.

Sukanya Banekar
SubratSubrat (Salesforce Developers) 
Nikhil Garg 17Nikhil Garg 17

Hi Sukanya,

Thanks for your response. so my use case is 

"I have a VF page that is calling the method of apex class, Apex class is looping over something but to overcome Apex CPU Time error I have break loop in batches and each batch is running as an Async transaction, I want that whenever an async class is called for every batch from apex class, the async class must return some response to the apex class. Because my apex class is returning responses to the vf page for some operations. But async classes can't return anything.
So I thought to follow the approach that, I can use Platform events to return an async class response to my vf page. so after processing of async class, it will publish my response using the platform event and I'll subscribe platform event on the vf page."

The code you have provided may work but I'm not able to find libraries of these APIs so that I can store them as a static resource.

Kindly help, if you find something different for this use case.

Thanks & Regards
Nikhil Garg

Sukanya BanekarSukanya Banekar
Hi Nikhil,

You mean to say JS and cometd libraries?
Nikhil Garg 17Nikhil Garg 17
Hi sukanya

Yes please share the links to download these libraries and the link you have shared for the cometD is not working.

If you have other approach for my use case then kindly suggest.