CodeBlanks Logo Icon CodeBlanks

pushState

JavaScript course · Advanced · Lesson 79/100

Learn to change the URL and add a new history entry without reload with pushState.

What is pushState?

history.pushState(state, unused, url) adds a new entry to the session history and changes the URL in the address bar, but it does not reload the page.

history.pushState({page: 'about'}, '', '/about');

The first parameter is the state object stored with the entry; you read it later from event.state. The second parameter is reserved for a title but browsers ignore it, so an empty string is common. The third parameter is the new URL and must be same-origin.

State, title and URL

The state object is a serializable value stored with the entry: an object, array, number or string. You read it later from history.state or event.state.

const state = { page: 'profile' };
history.pushState(state, '', '/profile');

The URL may be a relative path as long as it stays same-origin. Navigating to a different origin throws a SecurityError.

Exercise Add a new entry with pushState

Assign 'profile' to a page variable. Call history.pushState with the state { page: page }, an empty title and the URL '/profile'.

Show example solution
const page = 'profile';
history.pushState({ page: page }, '', '/profile');

Test yourself

  1. What does history.pushState do?

    • Adds a new history entry and changes the URL without reloading
    • Reloads the page
    • Deletes the history entry
    • Resizes the page
    Show answer

    Adds a new history entry and changes the URL without reloading — Correct! pushState both adds a new entry and changes the URL.

  2. Complete the pushState call

    const state = { page: 'profile' };
    ____;
    Show answer
    const state = { page: 'profile' };
    history.pushState(state, '', '/profile');
  3. Match the pushState concepts

    pushState
    adds a new entry
    state
    data stored with the entry
    url
    the address bar path
    unused
    the title parameter

All lessons in Advanced