skip to Main Content

I need to refresh the webpage refresh every time when a user resume at the page. actually when user open my website all data retrived and shown to user. when user go outside the browser or switch tabs data remain same so when user come back to my tab or reopen browser i want to reload or refresh the page . so user get updated data every time.

i tried all methods

2

Answers


  1. maybe you want to check out about websocket for showing realtime data for the ui. But since your asking how to refresh the page when user come back to the tab this maybe helps using visibilitychange events

    heres an example:

    window.addEventListener('visibilitychange', () =>{
        if (document.visibilityState === 'visible') window.location.reload();
        else console.log('user leaves the page')
    })
    

    the event will trigger when user leaves and enter the page so use if condition to execute your own code if you want.

    Login or Signup to reply.
  2. You can use the document.hasFocus() method to detect if the user is currently viewing the webpage. To continuously check for changes in the user’s focus state, you can use the setInterval() method.

    Here’s the code:

    let userIsViewingPage = true;
    
    setInterval(focusChecker, 500);
    
    function focusChecker() {
      if (document.hasFocus()) {
        if (!userIsViewingPage) {
          location.reload();
          userIsViewingPage = true;
        }
      } else {
        userIsViewingPage = false;
      }
    }

    I hope this is helpful to you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search