Nick Santos
Nick Santos

Reputation: 45

Can a service worker detect history navigation?

I have a service worker that displays a splash screen while the main content loads in the background.

Unfortunately, this makes the experience worse on history navigations (e.g., back button) because the splash screen loses the page state (e.g., scroll position).

Is there a way for the service worker to detect that a FetchEvent is for a history navigation?

Upvotes: 2

Views: 300

Answers (2)

Ashok
Ashok

Reputation: 607

Anyone interested in knowing if the request is history navigation or not, would be glad to know that now you should be able to detect this.

Here is the updated spec: https://fetch.spec.whatwg.org/#concept-request-history-navigation-flag

self.addEventListener('fetch',(event) => {
    if (event.request.isHistoryNavigation) {
        // Enter code related to history navgiation
    }
});

Upvotes: 0

Jeff Posnick
Jeff Posnick

Reputation: 56074

I believe that the Request object that's exposed via the FetchEvent interface won't have anything that specifically identifies it as being due to a history navigation. The mode attribute, for instance, will end up being set to 'navigate', which is the same value you'd see for navigations due to something other than a back button.

There is an isReload property on the FetchEvent, but the service worker specification goes out of its way to call out that only refreshes, and not history navigations, should result in a true value:

Pressing the refresh button should be considered a reload while clicking a link and pressing the back button should not. The behavior of the Ctrl+l enter is left to the implementations of the user agents.

Upvotes: 1

Related Questions