Socket
Socket
Sign inDemoInstall

history

Package Overview
Dependencies
28
Maintainers
1
Versions
101
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    history

A minimal, functional history implementation for JavaScript


Version published
Maintainers
1
Created

Package description

What is history?

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.

What are history's main functionalities?

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' }

Other packages similar to history

Readme

Source

build status npm package react-router channel on slack

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.

Installation

$ npm install history

Getting Started

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 API
  • createHashHistory is for use in legacy web browsers (see caniuse for compatibility)
  • createMemoryHistory is used mainly for testing and does not persist across sessions

Once 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();

Location

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

Support for query string parsing is provided using the enableQueries module.

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' });

Navigation

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();

Confirming Navigation

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
  }
});

Query Support

Support for parsing and serializing URL queries is provided by the enableQueries function. Simply wrap your history object and you'll have a parsed location.query object inside listen.

import { createHistory, enableQueries } from 'history';

var history = enableQueries(createHistory());

history.listen(function (location) {
  console.log(location.query);
});

Query-enabled histories also accept URL queries as trailing arguments to pushState, replaceState, and createHref.

history.pushState(null, '/the/path', { the: 'query' }); // /the/path?the=query

Caveats of Hash History

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.

Thanks

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.

Keywords

FAQs

Last updated on 17 Aug 2015

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc