JavaScript SSE onerror Event
You are Here:
JavaScript SSE onerror Event
The SSE onerror
event occurs when an error occurs with the event source.
Note: We provided PHP and Node.js server-side code to demonstrate the onerror
event. Please choose any one of your favorites.
PHP Server-Side Code
The following is the PHP server-side code used for the below examples.
sse.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date("d/m/Y H:i:sa");
echo "data:{$time}\n\n";
flush();
?>
Node.js Server-Side Code
The following is the Node.js server-side code used for the below examples.
sse.js
var express = require("express");
var app = express();
//Start of code for Server Sent Events
app.get("/sse", function(req,res){
res.writeHead(200, {
'Connection': 'keep-alive',
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache'
});
setInterval(function(){
res.write('data:'+ new Date()+ '\n\n');
}, 1000);
});
//End of code for Server Sent Events
app.listen(8000, function(){
console.log("port is listening to 8000");
});
onerror as Property
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h1>Live Data From Server</h1>
<div id="point"></div>
<script>
var x = document.getElementById("point");
if( typeof(EventSource) !== "undefined"){
var eventSource = new EventSource("sse.php");
eventSource.onopen = function(){
x.innerHTML += "Connection Opened<br>";
}
eventSource.onmessage = function(event) {
x.innerHTML += event.data + "<br>";
}
eventSource.onerror = function(){
x.innerHTML += "Connection Closed<br>";
}
}
else {
x.innerHTML = "Sorry, your browser does not support server sent events";
}
</script>
</body>
</html>
Syntax
As Property
eventSourse.onerror = function(event){
// WebSocket message received
}
Using Event Listener
eventSourse.addEventListener("error" , myScript);
Using Event Listener
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h1>Live Data From Server</h1>
<div id="point"></div>
<script>
var x = document.getElementById("point");
if( typeof(EventSource) !== "undefined"){
var eventSource = new EventSource("sse.php");
eventSource.onopen = function(){
x.innerHTML += "Connection Opened<br>";
}
eventSource.onmessage = function(event) {
x.innerHTML += event.data + "<br>";
}
eventSource.addEventListener("error", function(){
x.innerHTML += "Connection Closed<br>";
});
}
else {
x.innerHTML = "Sorry, your browser does not support server sent events";
}
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.