4

Currently in my page I am using this to refresh the page each minute:

<head>
...
<meta http-equiv="refresh" content="60" />
...
</head>

How instead, I want to refresh the page when a user presses the tab. Lets say a user has multiple tabs open in the web browser. And he uses a few minutes surfing on another tab. When he then press the tab for my website, I want the page to autorefresh, so the user don't have to do it himself to check for any updates on the page. How can I accomplish this?

unor
  • 92,415
  • 26
  • 211
  • 360
Anefi3
  • 41
  • 1
  • 3
  • https://stackoverflow.com/questions/20783015/refresh-page-when-clicked-on-link – s.kuznetsov Nov 03 '20 at 08:57
  • Note that when it's implemented the users experience can be rather unexpected and hence misleading. He had been on your site and after coming back it disappears, is empty for a while and hopefully loads again. – wiktus239 Nov 03 '20 at 08:57
  • you could put a javascript function onto your body tag with the onclick parameter then have the js funtion reload the page – an inconspicuous semicolon Nov 03 '20 at 08:59
  • @sergeykuznetsov I don't want to refresh when pressing a button or link on my page, but I want my page to refresh when the user presses the tab for my website (tabs on the top of the web browser). – Anefi3 Nov 03 '20 at 09:09
  • If I understand correctly, then the page refresh event should be triggered when switching to a tab (the tab is launched, but not active). And when the user visits this tab, the update is triggered. So? – s.kuznetsov Nov 03 '20 at 09:21
  • @sergeykuznetsov Yes, that is correct. Lets say the user has 3 tabs open in the browser. Facebook, YouTube and my website. The user changes from my website to Facebook. After a few minutes the user switches back to my tab, and then I want to page to automatically refresh, so the user don't have to press F5(or press refresh button) to refresh the page. – Anefi3 Nov 03 '20 at 09:24
  • 1
    Use @Andrea Viviani's answer. That's what you need. – s.kuznetsov Nov 03 '20 at 09:29

1 Answers1

5

you should use js and visibility API:

include this small script in your html page:

<script>
document.addEventListener("visibilitychange", function() {
   if (document.hidden){
       console.log("Browser tab is hidden")
   } else {
       console.log("Browser tab is visible")
       location.reload();
   }
});
</script>

Adapted from here: Event for when user switches browser tabs

Andrea Viviani
  • 217
  • 1
  • 6