I am trying to use navigator.sendBeacon()
when user is inactive. At the same time I will be sending to server side when user is inactive.
If I switch from the browser after the 6th sent beacon, my backend don't take the requests.
Client side:
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
const status = JSON.stringify({ status: "user is online" });
navigator.sendBeacon(
"http://localhost:5000/api/user/user-status",
status
);
} else {
const status = JSON.stringify({ status: "user is offline" });
navigator.sendBeacon(
"http://localhost:5000/api/user/user-status",
status
);
}
});
Server side:
userRouter.post("/user-status", async (request, response) => {
const body = request.body;
if (body) {
const obj = JSON.parse(body);
console.log("this is body:", obj);
}
});
To start console.log
again in server side, I have to restart the server, otherwise it won't log anything.