There are a few ways to refresh a client's browser from the server.
Server-Sent Events:
One simple method that works across browsers and servers uses server-sent events. The minimal process is:
- client sends a subscription request to server with EventSource():
var evtSource = new EventSource("<server_URL>/subscribe");
- client sets up a listener for incoming messages:
evtSource.onmessage = function () { myPageRefresh() };
On the server side, set up a handler for GET /subscribe
requests and keep track of the subscribed client:
const express = require('express');
const app = express();
var client = null;
app.get('/subscribe', (req, res) => {
// send headers to keep connection alive
const headers = {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache'
};
res.writeHead(200, headers);
// send client a simple response
res.write('you are subscribed');
// store `res` of client to let us send events at will
client = res;
// listen for client 'close' requests
req.on('close', () => { client = null })
});
// send refresh event (must start with 'data: ')
function sendRefresh() {
client.write('data: refresh');
}
Now the server can send a refresh event at any time by simply calling sendRefresh()
.
lite-server:
If you are running the server locally on your development computer, refreshing the browser is trivially easy. lite-server is a module that will refresh the browser whenever it detects a change to source files. It's very handy.