webSocketSend
Updated pdexter 2024-01-15
Available from Formbird v4.2.3
Function for the sending of WebSocket messages from server-side rulesets in Formbird. This function is essential for real-time communication between the server and client-side components in an application, as well as between different devices connected to the same WebSocket.
(server-side function)
Syntax
ft3.webSocketSend( { eventName : eventName, data : eventData } );
Part | Description |
---|---|
eventName | String; Unique name to identify the event. |
data | Object; any data needed to pass to the event receivers |
Client-side Event Listening
On the client-side, messages sent via this function can be intercepted using the WebSocketService
's addEventListener
method.
Example of Client-side Listener
window.FormbirdInjectorService.get('WebSocketService').addEventListener('testEvent', function(data) {
console.log(data);
});
Here, the client-side application listens for testEvent
. Upon receiving this event, the callback function is executed, logging the received data object to the console.
The OnLoad Ruleset is probably the best place to instantiate the listener.
Note The socket event itself will not evoke any client side ruleset event in itself at time of webSocketSend. Setting of document field values may trigger an OnFieldChange event as a consequence (providing the field value actually changes).
Example in a Rule
/// ONLOAD RULESET ////
ruleCreateWebSocketListener : {
ruleCondition : true,
ruleAction : function(ntf) {
const ft3 = ntf.scope;
// Create the function to run on the websocket event
const socketReaction = eventData => {
ft3.dialog({
title : 'WebSocket Event',
text : 'aaTestEvent was received!!' ,
type : 'success'
});
ntf.document.description = 'WebSocket Event received - ' + JSON.stringify(eventData.data);
};
const webSocket = window.FormbirdServiceInjector.get('WebSocketService');
webSocket.addEventListener('aaTestEvent', socketReaction);
}
},