| sidebar_position | 3 |
|---|
All available settings:
var sse = $.SSE('sse-server.php', {
onOpen: function (e) {},
onEnd: function (e) {},
onError: function (e) {},
onMessage: function (e) {},
options: {},
headers: {},
events: {}
});Fired when the connection is opened for the first time.
onOpen: function(e){
console.log("Connection opened");
console.log(e);
}:::note This callback is only triggered once when the connection is first established, not on reconnections. :::
Fired when the connection is closed and the client will no longer listen for server events.
onEnd: function(e){
console.log("Connection ended");
console.log(e);
}Fired when a connection error occurs.
onError: function(e){
console.log("Connection error occurred");
console.log(e);
}Fired when a message without an event name is received.
onMessage: function(e){
console.log("Message received:", e.data);
}Event object properties:
data: The message datalastEventId: The ID of the last event receivedorigin: The origin of the messagereturnValue: Alwaystrue
Configure the behavior of the SSE instance:
options: {
forceAjax: false
}- Type:
boolean - Default:
false
Forces the use of Ajax polling even if the EventSource object is natively supported by the browser.
var sse = $.SSE('sse-server.php', {
options: {
forceAjax: true
},
onMessage: function(e){
console.log(e.data);
}
});Send custom headers with the request:
headers: {
'Authorization': 'Bearer 1a234fd4983d',
'X-Custom-Header': 'value'
}:::warning Important
EventSource does not support custom headers. When you provide custom headers, the plugin will automatically fallback to forceAjax=true, even if it's not explicitly set.
:::
Example:
var sse = $.SSE('sse-server.php', {
headers: {
'Authorization': 'Bearer 1a234fd4983d'
},
onMessage: function(e){
console.log(e.data);
}
});Define handlers for custom server-sent events:
events: {
myEvent: function(e) {
console.log('Custom Event received');
console.log(e.data);
},
anotherEvent: function(e) {
console.log('Another event');
console.log(e.data);
}
}var sse = $.SSE('sse-server.php', {
events: {
myEvent: function(e) {
console.log('Custom Event:', e.data);
}
}
});
sse.start();The event name must match the key in the events object:
echo "event: myEvent\n";
echo "data: My Message\n";
echo "\n";Server-sent events follow this format:
event: eventName
data: message content
id: unique-id
retry: 3000
- event: Optional event name (if omitted, triggers
onMessage) - data: The message content
- id: Optional unique identifier
- retry: Optional reconnection time in milliseconds
- Two newlines (
\n\n) signal the end of a message