简体   繁体   中英

How to detect when a user is viewing a webpage using javascript

I have a webpage which I want to display users who have that page opened. (I'm using node.js for server side)

My current attempt:

On server side, there's a counter that counts the amount of time he submits the GET request to that webpage. Hence if he opens that page more than once, counter++

Everytime the user leaves the webpage, it sends a websocket to the server using socket.io.

window.onbeforeunload = function() { 
    socket.emit('ClosePage');
}

Then on the server side, when it receives this socket, it decreases his counter by 1, aka counter--

So using this logic, it's possible to detect when an user has the webpage opened and when he actually closes the webpage for real.

HOWEVER , the problem occurs when an user refreshes the page like crazy, the server will just adds up continuously the counter without decreasing it afterward, because the window has not unloaded yet (my guess).

Does anyone know how to fix stuffs like this? Or does anyone know what algorithm does most forums use when they display users or strangers who are reading a post?

Thanks a lot!

You could drop a cookie and not increment the count if the cookie exists. Or you could block on IP, but that might knock out some genuine views.

You're right about that regarding the delay before it decrements the value. This will be correlated with the connection timeout value in socket.io. You can't guarantee that every user will be using websockets. If they are using XHR-polling or other types of transport layers it will have to timeout before decrementing. Websocket users will cause the change immediately.

Google Analytics(分析)可以实时显示您网站上的用户以及他们正在查看的内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM