Home > Enterprise >  How to check if someone is currently on the website (online) using JS?
How to check if someone is currently on the website (online) using JS?

Time:07-05

I am building a website with chat etc. The problem is I cannot correctly define if someone is currently on the website which cause I cannot set their activity.

I wrote a function which is invoked by the body tag in HTML file <body onl oad="changeStatus(true)" onunload="changeStatus(false)"> but as I said it seems not to work.

When the status of the first users sets to the online value, the second one immediately changes to offline. When I try to type something in the input on the website it also changes the status to offline, it doesn't matter who is typing.

I am currently thinking of writing this part in PHP just using the session, but maybe someone knows how to do this in JS?

function changeStatus(event) {
  if (event) {
    db.ref("status/"   username   "/"   receiver).set({
      act: "online"
    });
  } else {
    db.ref("status/"   username   "/"   receiver).set({
      act: "offline"
    });
  }
}

CodePudding user response:

Are you trying to determine if the page has loaded? If so then a simple jquery document load on will do that

https://learn.jquery.com/using-jquery-core/document-ready/

  <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
    $( window ).on( "load", function() {
        console.log( "window loaded" );
    });
//or
$(function() {
    console.log( "ready!" );
});
    </script>

if your trying to capture if the user is on the page then mouse over or mouse click might be better

https://api.jquery.com/mouseover/

https://api.jquery.com/click/

I hope this helps

CodePudding user response:

It sounds like you're trying to build a presence system, in which case I recommend checking out the Firebase documentation on managing presence, how onDisconnect works, detecting connection state and the sample presence app.

  • Related