use-history-back-trap
v1.0.9
Published
Intercepts browser's back navigation allowing to resume it later if needed
Downloads
21
Maintainers
Readme
use-history-back-trap
by Vytenis Urbonavičius
use-history-back-trap is a React hook which can intercept native browser's navigation backwards in history. After navigation is intercepted and paused, it may later be resumed if needed.
By default browser navigation cannot be intercepted. use-history-back-trap uses a work-around to achieve interception by manipulating history object.
Use Case
Main use case is to prevent data loss if user is filling some form and then clicks "back" on browser's UI.
This should be obvious to everyone BUT I will highlight this just in case - do not use and abuse this tool for any malicious purposes such as preventing navigation on scam websites.
Limitations
Interception may not work if user has not interacted with page in any way (clicked or typed something).
If user attempts to navigate back for the second time in quick succession - second action might not be intercepted. This depends on whether "handleTrap" callback (see example below) finishes work soon enough to get ready for second interception.
Installation
npm install use-history-back-trap
Usage
import {useHistoryBackTrap} from 'use-history-back-trap'
const SomeFunctionalReactComponent = () => {
useHistoryBackTrap(handleTrap)
// < ... >
}
You need to provide implementation of handleTrap based on what you want to achieve.
Example of callback implementation:
// Note that this callback can be used async if needed
const handleTrap = async resume => {
if (window.confirm('Are you sure?')) {
resume() // triggers navigation which was suspended
return true // tells that trap does NOT need to be setup again
} else {
return false // tells that trap needs to be setup again
}
}
Additional options
useHistoryBackTrap accepts a second argument with additional options. All of them are optional. They are mainly designed to prevent clashes with other potential hacks in large projects - in most cases these options are not needed.
useHistoryBackTrap(handleTrap, {
// Below options specify keys added into window.history.state.
// They are used to identify navigation trap when history pop is detected.
// If you do not know what that means - you do not need to change :)
trapFlag: 'backTrap',
trapTime: 'backTime',
})
Happy Hacking!!!