Is it possible to block users from leaving a page on a single page app? 🤔


Remove history.block

  • Routing on SPA vs Traditional web page routing
  • History API
  • window.popstate event
  • history blocking strategy from React Router

Traditional Routing

- 1 URL would be tied to a single page and routing is handled on server side


- 'beforeunload' event is fired and this event is cancellable

SPA routing

- handled by the SPA itself


- on matching a route, it has to re-render the app itself


- URL and document are independent of each other

History API

  • Allows us to reuse active document
  • It can update the URL and simultaneously add this new URL location into the browser history session
  • store a state with a URL location
  • has an API 'go()' that allows us to call the browser's back or forward action

History API

  • You CANNOT manipulate the history object
  • You WILL NOT know the previous locations

popstate event

  • fired when the user navigates between 2 history entries for the same document
  • event is NOT cancellable
  • URL location changes before popstate event is sent
  • doesn’t tell us whether the back button or forward button triggered it

History blocking strategy

  1. On page load, instantiate an array. This array will be used to track the history location.
    Let the first page we are be index 0
  2. When popstate occurs, the URL location would have changed. We get the new URL location state and give it
    index + 1
  3. We are now on the redirected page. Navigate back to current page with go(currentPageIndex - redirectedPageIndex)
  4. When user wishes to stay on page, no redirection will be called. When user wishes to leave page, go(delta * -1)

Is history blocking possible?

Use history state as the array!

  • ✅ Refresh Issue
  • ✅ Browser action
  • location.href?

Case 1:

use location.href intermittently 

Case 2:

Navigate completely with location.href

Does history blocking work on a SPA?

  1. Navigate within the SPA with history library’s push instead of the browser’s history API
  2. Try not to use location.href to navigate within the SPA
  3. Browser must support history API
Made with