How to handle long-lived browser tabs with the Page Visibility API

You open an enterprise portal at 9:00 AM. You work on it for a while, then switch to another application. The portal stays open in a browser tab. Hours later, you come back. The page is still there. It looks completely normal.

You click a button.

Nothing happens.

You click again.

Still nothing.

Maybe a dropdown doesn’t open. Maybe a request never completes. Maybe a component feels sluggish. Maybe something that worked perfectly in the morning suddenly behaves strangely.

So you refresh the page.

Everything works again.

If you’ve worked with large enterprise web applications, you’ve probably encountered some version of this.

The application wasn’t necessarily “broken.”

The browser had simply been optimizing a page that had been sitting unused for hours.

And this creates an interesting problem for enterprise applications: how do you gracefully handle a web application that users leave open for long periods of time?

Originally published on Medium in Level Up Coding.

The Enterprise Tab Problem

Enterprise applications are different from many consumer websites.

A typical consumer website might be opened, used for a few minutes, and closed.

Enterprise applications can have a very different lifecycle.

A user might:

  • Open the application at the beginning of their workday.
  • Keep the tab open for eight hours.
  • Switch between several applications.
  • Return to the portal occasionally.
  • Leave it in the background overnight.
  • Open multiple instances of the same portal.
  • Expect everything to work exactly as it did when they left.

This creates a situation where the lifetime of the browser tab can be much longer than the lifetime of the application’s internal state.

Your JavaScript application may have been initialized hours ago.

Your authentication token may have expired.

Your API connection may no longer be usable.

Your browser may have throttled background execution.

The browser may even have discarded parts of the page under memory pressure.

Yet from the user’s perspective, there is still just a tab sitting there.

And when they return, they naturally expect it to work.

What Happens to a Background Tab?

Modern browsers are very good at managing resources.

Keeping every tab running at full speed all the time would waste CPU, memory, battery, and network resources.

So browsers can aggressively optimize pages that aren’t currently visible.

Depending on the browser, operating system, and available resources, a background page can experience things such as:

  • JavaScript timer throttling
  • Reduced CPU activity
  • Suspended or frozen page execution
  • Network activity being affected
  • Memory pressure causing a page to be discarded
  • Resources needing to be restored when the page becomes active again

This is normally a good thing.

If I have 30 tabs open and I’m only using one of them, I don’t want all 30 applications consuming CPU continuously.

The problem is that enterprise applications are often designed with the assumption that their application state remains continuously available.

That’s not always a safe assumption.

The Authentication Token Problem

There is another problem that often appears with long-lived tabs: authentication tokens expire.

Imagine that your application obtains an access token when the user logs in.

The user works normally for a while.

Then they leave the application in the background for several hours.

When they eventually return, the access token may have expired.

If we simply send the next API request with that expired token, the backend will reject it with a 401 Unauthorized.

One way to handle this is to let the request fail and refresh the token after receiving the 401.

But I prefer a more proactive approach:

Check whether the token is about to expire before sending the request.

If you’re using Axios, this can be handled elegantly with a request interceptor.

When we obtain the token, we already know its expiration time. We can store that information alongside the token.

For example:

interface AuthToken {
  accessToken: string
  expiresAt: number
}

The expiresAt value can represent the expiration time as a Unix timestamp.

Then, before every HTTP request, the Axios interceptor can check whether the existing token is still valid.

Conceptually:

axios.interceptors.request.use(async (config) => {
  const token = getStoredToken()

  if (!token) {
    return config
  }

  const isExpired = Date.now() >= token.expiresAt

  if (isExpired) {
    const refreshedToken = await refreshTokenSilently()
    storeToken(refreshedToken)
    config.headers.Authorization = `Bearer ${refreshedToken.accessToken}`
    return config
  }

  config.headers.Authorization = `Bearer ${token.accessToken}`
  return config
})

The important part here is the await.

The interceptor can pause the outgoing request while the application silently obtains a fresh token.

Only after the new token has been obtained do we allow the original request to continue.

Conceptually, the lifecycle becomes:

User returns to the application
            ↓
Application makes an API request
            ↓
Axios request interceptor runs
            ↓
Is the token expired?
       ↙              ↘
     No                Yes
      ↓                 ↓
Attach token       Refresh silently
      ↓                 ↓
      └──────────┬──────┘
                 ↓
       Send original request

This has an important advantage over waiting for a 401.

The application doesn’t need to intentionally make a request that we already know is going to fail.

Instead, authentication freshness is handled before the request reaches the backend.

Of course, the exact implementation depends on your authentication provider and token lifecycle. You may also want to refresh slightly before the actual expiration time rather than waiting until the exact expiry timestamp, to account for network latency and clock differences.

For example, you could consider a token stale when it has less than a few minutes remaining.

This gives us a clean separation of responsibilities:

  • Authentication freshness is handled by the HTTP/authentication layer.
  • Application freshness is a separate problem.

Even if the token is successfully refreshed, the frontend application itself may still have been sitting in the background for several hours.

And that’s where the stale-tab problem begins.

A Stale Application Is a Different Problem

Consider this scenario.

The user hasn’t touched the application for six hours.

They return.

Their authentication token is refreshed successfully.

The next API request works.

But the UI still behaves strangely.

Why?

Because authentication is only one part of the application.

A large frontend application can have many pieces of state:

  • Component state
  • Pinia/store state
  • Cached API responses
  • WebSocket connections
  • Event listeners
  • Timers
  • Background polling
  • Third-party libraries
  • Browser resources
  • Loaded application chunks
  • Client-side routing state

Some of those things may no longer represent a healthy application state after a very long period of inactivity.

This is what I mean by a stale application.

The application hasn’t necessarily crashed.

It has simply been alive for much longer than the lifecycle you originally expected.

Why Refreshing Can Sometimes Be the Right Solution

As frontend developers, we often try to make applications recover from everything.

And that’s usually a good instinct.

But there is a point where recovery logic becomes more complicated than simply starting the application again.

Think about what a full page refresh gives you:

  • JavaScript is loaded again.
  • Application state is initialized again.
  • Routes are reconstructed.
  • API clients are recreated.
  • Resources are requested again.
  • Authentication state is re-established.
  • The application starts from a known state.

In other words:

A refresh gives the application a clean lifecycle.

For a complex enterprise portal that has been sitting untouched for hours, that can be a very reasonable recovery strategy.

The key is to do it deliberately and gracefully, rather than surprising the user.

Why setTimeout() Isn’t Enough

The first solution that might come to mind is simple:

setTimeout(() => {
  refreshApplication()
}, 60 * 60 * 1000)

Wait one hour, then refresh.

Unfortunately, this isn’t a reliable way to detect one hour of user inactivity.

The problem is that the browser controls how background pages are executed.

When your page becomes hidden, JavaScript timers may be throttled or otherwise deprioritized.

So if you write:

setTimeout(() => {
  console.log('One hour passed')
}, 60 * 60 * 1000)

you are essentially assuming:

“The browser will allow my JavaScript to execute exactly one hour from now.”

That’s not something you should rely on for background tabs.

The timer might execute later than expected.

The page might be frozen.

The page might be discarded.

The user might come back before the timer executes.

And even if the timer does eventually execute, it doesn’t really answer the question we care about.

The question isn’t:

“Did my JavaScript timer run for an hour?”

The question is:

“How long was the user away from this application?”

That’s a different problem.

The Better Approach: visibilitychange

Fortunately, browsers provide an API specifically designed for this kind of scenario: the Page Visibility API.

The most useful part for our case is the visibilitychange event.

We can listen for changes to:

document.visibilityState

which can be:

  • 'visible'
  • or 'hidden'

For example:

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    // The page is no longer visible
  }

  if (document.visibilityState === 'visible') {
    // The user has returned
  }
})

This gives us something much more useful than a timer.

We know when the page became hidden.

And we know when it became visible again.

Now we can measure the actual elapsed time.

Store a Timestamp, Not a Timer

When the page becomes hidden, record the current time.

let hiddenAt: number | null = null

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    hiddenAt = Date.now()
  }
})

Then when the user returns:

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible' && hiddenAt) {
    const inactiveFor = Date.now() - hiddenAt
    console.log(`Inactive for ${inactiveFor}ms`)
    hiddenAt = null
  }
})

Now we’re no longer asking the browser to execute something after an hour.

We’re simply comparing two timestamps.

For example:

Page hidden:
09:15:32

Page visible:
14:42:18

The browser doesn’t need to continuously execute JavaScript during those five hours.

When the user returns, we can calculate:

14:42:18 - 09:15:32

and determine how long the application was actually hidden.

This is a much more robust approach.

Adding an Inactivity Threshold

Now we can define a threshold.

For example:

const ONE_HOUR = 60 * 60 * 1000

Then:

let hiddenAt: number | null = null

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    hiddenAt = Date.now()
    return
  }

  if (document.visibilityState === 'visible' && hiddenAt) {
    const inactiveFor = Date.now() - hiddenAt

    if (inactiveFor >= ONE_HOUR) {
      // Application has been inactive for too long
    }

    hiddenAt = null
  }
})

This gives us a simple rule:

If the application has been hidden for more than one hour, consider it stale.

The actual threshold doesn’t have to be one hour.

It depends on the application.

For some applications, 15 minutes might be appropriate.

For others, 2 hours might make more sense.

The important part is that the threshold should be based on the application’s expected lifecycle.

Don’t Automatically Refresh Without Warning

There’s one important UX problem with the refresh strategy.

Imagine a user comes back after two hours and your application immediately executes:

window.location.reload()

That could be a terrible experience.

The user might have:

  • Unsaved form data
  • A partially completed workflow
  • A draft
  • A selected configuration
  • Filters they spent time setting up

A silent refresh can destroy that state.

Instead, I prefer prompting the user.

Something like:

You’ve been away for a while

This application has been inactive for more than an hour. Refresh the application to make sure everything is up to date.

Refresh application

This gives the user control.

And it communicates what is happening instead of making the application appear to randomly reload.

What About Unsaved Work?

This is probably the most important consideration before implementing this pattern.

A stale-tab strategy should never blindly assume that refreshing is safe.

For a read-only dashboard, refreshing after an hour might be completely harmless.

For a data-entry portal, it could be dangerous.

Consider a user who spends 45 minutes filling out a complex form.

They switch tabs for an hour to gather some information.

They come back.

Your application detects the inactivity and refreshes.

Their work is gone.

That’s unacceptable.

So the implementation should consider whether the user has unsaved changes.

For example:

if (isApplicationStale && !hasUnsavedChanges) {
  showRefreshPrompt()
}

Or, if there are unsaved changes, you could show a stronger warning:

This application has been inactive for a long time. You have unsaved changes. Please save your work before refreshing.

The exact behaviour depends heavily on the application.

Turning It Into a Reusable Vue Composable

If you’re using Vue, this logic can be extracted into a reusable composable.

Something like:

import { onMounted, onUnmounted, ref } from 'vue'

export function useTabInactivity(
  threshold = 60 * 60 * 1000,
) {
  const isStale = ref(false)
  const inactiveFor = ref(0)

  let hiddenAt: number | null = null

  const handleVisibilityChange = () => {
    if (document.visibilityState === 'hidden') {
      hiddenAt = Date.now()
      return
    }

    if (document.visibilityState === 'visible' && hiddenAt) {
      inactiveFor.value = Date.now() - hiddenAt
      isStale.value = inactiveFor.value >= threshold
      hiddenAt = null
    }
  }

  onMounted(() => {
    document.addEventListener(
      'visibilitychange',
      handleVisibilityChange,
    )
  })

  onUnmounted(() => {
    document.removeEventListener(
      'visibilitychange',
      handleVisibilityChange,
    )
  })

  return {
    isStale,
    inactiveFor,
  }
}

Then your application can decide what to do with that information.

For example:

const { isStale } = useTabInactivity()

And your UI can react accordingly.

This separation is useful because the composable doesn’t need to know how your application should recover.

It simply answers:

“Has this tab been inactive for too long?”

The application can then decide whether to:

  • Refresh
  • Show a modal
  • Reinitialize some state
  • Reconnect a WebSocket
  • Refresh data
  • Ask the user to log in again
  • Do nothing

Refresh Everything or Recover Selectively?

A full refresh isn’t always the best solution.

It’s simply one possible solution.

For a relatively simple application, you might only need to refresh your data:

Tab becomes visible
        ↓
Was hidden > 1 hour?
        ↓
       Yes
        ↓
Refresh API data

For a more complex application, you might need:

Tab becomes visible
        ↓
Was hidden > 1 hour?
        ↓
       Yes
        ↓
Check authentication
        ↓
Reconnect services
        ↓
Refresh application state

And for an application where you can’t guarantee that all state can be recovered correctly:

Tab becomes visible
        ↓
Was hidden > 1 hour?
        ↓
       Yes
        ↓
Ask user to refresh

There’s no universally correct answer.

The right strategy depends on how much state your application maintains and how safely that state can be reconstructed.

A Useful Mental Model

I think about long-lived browser tabs in terms of three separate problems.

1. Authentication freshness

“Is my user’s session/token still valid?”

Handle this at the authentication/API layer.

For example, Axios interceptors can detect authentication failures and refresh tokens where appropriate.

2. Application freshness

“Is the application itself still in a healthy state?”

This is where stale tabs become interesting.

A successful API request doesn’t necessarily mean the entire frontend is healthy.

3. Data freshness

“Is the information displayed to the user still current?”

This might require refetching data when the user returns.

These are different problems and shouldn’t necessarily be solved with the same mechanism.

Don’t Blame the Browser

It’s tempting to think:

“The browser broke my application.”

But that’s not really what’s happening.

The browser is doing exactly what it’s designed to do.

If a tab hasn’t been visible for several hours, aggressively optimizing it is reasonable.

The application is the thing making an assumption:

“Once I initialize, I can remain alive indefinitely.”

Modern browsers don’t guarantee that.

So instead of fighting the browser, we should design our applications around the browser’s lifecycle.

The Bigger Lesson

The web isn’t a place where your JavaScript gets to run continuously forever.

A browser tab has a lifecycle.

It can become visible.

It can become hidden.

It can be throttled.

It can be frozen.

It can potentially be discarded.

And eventually, it can be closed.

For short-lived applications, these details might never matter.

For enterprise applications that users keep open for eight, ten, or even more hours, they become much more important.

That’s why handling long-lived tabs should be considered part of application design rather than an unusual edge case.

Final Thoughts

The solution I ended up preferring is deliberately simple.

I don’t try to predict exactly what the browser did while the application was in the background.

I don’t rely on a timer running continuously for an hour.

Instead:

  • Listen for visibilitychange.
  • Record when the page becomes hidden.
  • When it becomes visible again, calculate the elapsed time.
  • If the inactive period exceeds a reasonable threshold, consider the application stale.
  • Let authentication interceptors handle expired tokens independently.
  • Decide whether the application can safely recover itself.
  • If not, ask the user to refresh.
  • Never blindly destroy unsaved user work.

The important idea isn’t really “refresh the page after one hour.”

It’s this:

Design your enterprise web application with the assumption that the browser may put it to sleep while the user is away.

Once you start thinking about the browser tab as having its own lifecycle, a lot of these seemingly random “the portal was working five hours ago, but now it’s acting weird” problems become much easier to reason about.

And sometimes, the best recovery strategy isn’t a complicated recovery system.

Sometimes, it’s simply giving the application a chance to start fresh.

Thanks for reading.

Happy coding!