Better-State
Including "Not Going Back"
This is a small wrapper that encapsulates
Features
-
View the browser history[^1] for your app.
-
Prevent the use of the browser's back and forward buttons.
-
Includes the current window.scroll for conveneince (useful when using History.scrollRestoration = 'manual')
Installation
npm install better-state
Setup
import betterState from "better-state";
Usage
To change the current browser URL and add to the browser history:
betterState.pushState(url)
betterState.pushState(url,{--some consumer-data})
To prevent the use of the browser's back and forward buttons:
betterState.preventBack = true
betterState.preventForward = true
To get the current known history[^1]:
betterState.history
To subscribe to popstate events (i.e. back and forward button clicks...)
betterState.on("state-change", (e) => { console.log(e); });
returns:
- back: [ true | false ] if the back button was pressed.
- forward: [ true | false ] if the back button was pressed.
- prevented: [ true | false ] if the pop was prevented.
- forced: [ true | false ] if the pop was forced[^2]
- state: {Object} including:
- url
- scrollX
- scrollY
- data: {Object} any consumer data
To override preventBack
and preventForward
:
betterState.forceForward()
betterState.forceBack()
To replace the current state:
(i.e. to change the current URL without adding to the browser history)
betterState.replaceState(url)
betterState.replaceState(url,{--some consumer-data})
To get the current state:
betterState.state
[^1] Only includes better-state history.
[^2] See forceBack() and forceForward().