better-history-api

1.0.1 • Public • Published

I needed to interact with the browser's History object, but it was too mind-bending. So I made this abstraction and then I was able to get my job done.

These functions update and return state using a single property on the real state object, minimizing your odds of bashing history state set by some other part of your app when you use this API.

API

const historyState = require('better-history-api')

historyState.update(newState)

Updates the existing state for the current history item.

The new state object you pass in is merged with the existing state with Object.assign.

state = historyState.get()

Returns the state object for the current history item.

historyState.addBeforePushStateMiddleware(fn)

This adds a callback/middlewarey function that will be called before pushState is called, no matter who is calling pushState.

Your function will be passed the current (pre-pushState) state, and will give you a chance to change it before the history stack changes.

historyState.addBeforePushStateMiddleware(
	state => Object.assign(state, { position: currentScrollPosition() })
)

Events

The historyState object is an event emitter that emits these events:

new state

Emitted immediately after pushState is called, while the state object is fresh and shiny.

old state

Emitted whenever a popstate event happens with any associated state. Emits the state object.

License

WTFPL

Readme

Keywords

Package Sidebar

Install

npm i better-history-api

Weekly Downloads

1

Version

1.0.1

License

WTFPL

Unpacked Size

3.84 kB

Total Files

3

Last publish

Collaborators

  • tehshrike