Security News
NIST Misses 2024 Deadline to Clear NVD Backlog
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
The history package is a JavaScript library that lets you manage session history anywhere JavaScript runs. It provides a minimal API that lets you manage the history stack, navigate, and persist state between sessions. It is commonly used in conjunction with libraries like React Router but can be used standalone as well.
Manage session history
This feature allows you to create a history object and manipulate the browser's session history by pushing new entries onto the history stack.
const { createBrowserHistory } = require('history');
const history = createBrowserHistory();
history.push('/home', { some: 'state' });
Navigate programmatically
This feature enables you to navigate through the history stack programmatically, either going back or forward.
history.go(-1); // Go back one entry in the history stack
history.goForward(); // Go forward one entry in the history stack
Listen for changes to the current location
This feature allows you to listen for changes in the current location, which is useful for reacting to navigation events.
const unlisten = history.listen((location, action) => {
console.log(action, location.pathname, location.state);
});
// To stop listening
unlisten();
Persist state between sessions
This feature allows you to push state onto the history stack and access it later, which is useful for persisting information across sessions without using local storage or cookies.
history.push('/location', { user: '12345' });
// The state can be accessed later
const location = history.location;
const state = location.state; // { user: '12345' }
React Router is a collection of navigational components that compose declaratively with your application. It provides bindings to the history library, making it easier to use with React applications. It is more feature-rich and tailored specifically for React, compared to the more general-purpose history package.
Vue Router is the official router for Vue.js. It deeply integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. It provides similar functionalities for managing navigation and history in Vue applications, analogous to what history does for more general JavaScript applications.
Reach Router is a small, simple router for React that borrows from the ideas of the history package. It provides easy route definition and navigation but has been officially replaced by React Router as of version 6.
Navigo is a simple vanilla JavaScript router with a similar API to history. It provides a powerful router with a small footprint that does not necessarily rely on the history API provided by the browser.
history
is a JavaScript library that lets you easily manage session history in browsers, testing environments, and (soon, via React Native) native devices. history
abstracts away the differences in these different platforms and provides a minimal API that lets you manage the history stack, navigate, confirm navigation, and persist state between sessions. history
is library-agnostic and may easily be included in any JavaScript project.
$ npm install history
The first thing you'll need to do is create a history object. history
provides several different create*
methods that you can use depending on your environment.
createHistory
is for use in modern web browsers that support the HTML5 history APIcreateHashHistory
is for use in legacy web browsers (see caniuse for compatibility)createMemoryHistory
is used mainly for testing and does not persist across sessionsOnce you get a history
object, use history.listen
to be notified when the location
changes.
import { createHistory } from 'history';
var history = createHistory();
// Listen for changes to the current location. The
// listener is called once immediately.
var unlisten = history.listen(function (location) {
console.log(location.pathname);
});
// When you're finished, stop the listener.
unlisten();
A location
object is conceptually similar to document.location
in web browsers, with a few extra goodies. location
objects have the following properties:
pathname The pathname portion of the URL, without query string
search The query string portion of the URL, including the ?
state An object of data tied to this location
action One of PUSH, REPLACE, or POP
key A unique identifier for this location
If you'd like, you can create a location
object programmatically using createLocation
.
import { createLocation } from 'history';
var location = createLocation('/a/path?a=query', { some: 'state' });
You can also use a history
object to programmatically change the current location
using the following methods:
pushState(state, path)
replaceState(state, path)
setState(state)
go(n)
goBack()
goForward()
The path
argument to pushState
and replaceState
represents a complete URL path, including the query string. The state
argument should be a JSON-serializable object. In setState
, the properties in state
are shallowly merged into the current state.
// Push a new entry onto the history stack.
history.pushState({ some: 'state' }, '/home');
// Replace the current entry on the history stack.
history.replaceState({ some: 'other state' }, '/profile');
// Go back to the previous history entry. The following
// two lines are synonymous.
history.go(-1);
history.goBack();
Sometimes you may want to prevent the user from going to a different page. For example, if they are halfway finished filling out a long form, and they click the back button (or try to close the tab), you may want to prompt them to confirm they actually want to leave the page before they lose the information they've already entered. For these cases, history
lets you register transition hooks that return a prompt message you can show the user before the location changes. For example, you could do something like this:
history.registerTransitionHook(function () {
if (input.value !== '')
return 'Are you sure you want to leave this page?';
});
You can also simply return false
to prevent a transition.
In browsers, history
uses window.confirm
by default to display confirmation messages to users. However, you can provide your own custom confirmation dialog box using the getUserConfirmation
hook when you create your history
object.
var history = createHistory({
getUserConfirmation: function (message, callback) {
callback(window.confirm(message)); // The default
}
});
Using window.location.hash
is a common trick that is used to mimic the HTML5 history API in older browsers. It works for most use cases and provides good compatibility across a wide range of browsers. However, in order to preserve state across browser sessions we need a place to store some state. HTML5 gives us the pushState
method and the popstate
event, but in older browsers the only thing we have is the URL. So, when using hash history, you'll see an extra item in your query string that looks something like _k=123abc
. This is a key that history
uses to look up persistent state data in window.sessionStorage
between page loads. If you prefer to use a different query parameter, or to opt-out of this behavior entirely, use the queryKey
configuration option.
// Use _key instead of _k.
var history = createHashHistory({
queryKey: '_key'
});
// Opt-out of persistent state, not recommended.
var history = createHashHistory({
queryKey: false
});
One other thing to keep in mind when using hash history is that you cannot also use window.location.hash
as it was originally intended, to link an anchor point within your HTML document.
A big thank-you to Dan Shaw for letting us use the history
npm package name! Thanks Dan!
Also, thanks to BrowserStack for providing the infrastructure that allows us to run our build in real browsers.
FAQs
Manage session history with JavaScript
The npm package history receives a total of 6,537,446 weekly downloads. As such, history popularity was classified as popular.
We found that history demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.