JavaScript SSE onopen Event

You are Here:

JavaScript SSE onopen Event

The SSE onopen event occurs when a connection with an event source is opened.

Note: We provided PHP and Node.js server-side code to demonstrate the onopen 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"); });

onopen 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(event){ x.innerHTML += "Connection Opened<br>"; } } else{ x.innerHTML = "Sorry, your browser does not support server sent events"; } </script> </body> </html>

Syntax

As Property

eventSourse.onopen = function(event){ // WebSocket message received }

Using Event Listener

eventSourse.addEventListener("open" , 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.addEventListener("open", function(event){ x.innerHTML += "Connection Opened<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.

Share this Page

Meet the Author