Is it possible to block users from leaving a page on a single page app? 🤔
@heyjiawei
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
- 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
 - When popstate occurs, the URL location would have changed. We get the new URL location state and give it
index + 1
 - We are now on the redirected page. Navigate back to current page with go(currentPageIndex - redirectedPageIndex)
 - 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?
- Navigate within the SPA with history library’s push instead of the browser’s history API
- Try not to use location.href to navigate within the SPA
- Browser must support history API
Is it possible to block users from leaving a page on a single page app? 🤔
By Chong Jia Wei
Is it possible to block users from leaving a page on a single page app? 🤔
- 718