Dharani.reddy
Dharani.reddy

Reputation: 13

How does an Express.js server knows if a browser closes or reloads?

I am working on a project with Express.js server. How can this server know if any one of its users(browser) is closed or reloaded??

Upvotes: 1

Views: 736

Answers (1)

jfriend00
jfriend00

Reputation: 707466

There is no generic way for a web server to know if a page has been closed in the browser as the browser does not automatically notify the server of that action and most web-sites do not need to know. A browser reload will show up on the server as a newly requested page load.

The more common method of detecting actions within a user's page is to use client-side Javascript and then make ajax calls to the server when interesting things happen that you want to tell the server about.

If you're trying to detect when a browser window/page is closed, one common way that is used to detect if a page has been closed in the browser is to use a webSocket or socket.io connection to the server. This connection is continuous for as long as the page is active, but whenever the browser closes that page (user navigates somewhere else, reloads, closes the tab, closes the browser, etc...), then the browser will close the webSocket or socket.io connection to the server and the server can use that as a notification that the page has been closed in the browser.

Of course, if the user is doing a reload, then the server will see the websocket or socket.io connection close, then see a request for a fresh copy of the page, then see a new webSocket or socket.io connection established. If you want to discern the different between a page close and a reload, then you would typically use some sort of timer with a user cookie. When you see the original webSocket or socket.io connection close, you set a timer for some short period of time (like 1 second) and if that user does not load the page and re-establish a new webSocket/socket.io connection within the next second, then it must be a page close activity rather than a page reload. If you do see a new page request from that user within that 1 second, then it must have just been a page reload. Usually a cookie is used to tag which user is making the request.

Upvotes: 1

Related Questions