I want to write a js that counts how long users stay on the page. There are currently two methods, but neither is ideal.
Timer, use ajax to send data to the database at certain intervals. This method cannot guarantee accuracy and will affect efficiency
Use the onunload event to send data when the user closes the window. However, a dialog box will pop up in chrome to prompt whether to leave the page, which is very unfriendly to users visiting the website
How to solve it
If you want to be very accurate, you can consider using
websocket
to maintain a long connection with the backend?