Edit this page

API Restoring history

Unpoly lets the user restore a previous history entry, usually by pressing the browser's back button.

Default restoration behavior

When the user navigates back to a history entry, Unpoly will usually update the <body> with HTML loaded from the restored location.

The exact process goes like this:

  • Check whether Unpoly owns the location.
  • Emit up:location:changed to see if another script wants to handle the location change.
  • Test which parts of the location changed.

If only the #hash changed from the previous location, Unpoly will scroll to a matching fragment and end the process.

If the location's path or query string changed:

Custom restoration behavior

Listeners to up:location:restore may mutate the event.renderOptions event to customize the render pass that is about to restore content:

up.on('up:location:restore', function(event) {
  // Update a different fragment when restoring /special-path  
  if (event.location === '/special-path') {
    event.renderOptions.target = '#other'
  }
})

You may also substitute Unpoly's render pass with your own restoration behavior, by preventing up:location:restore. This will prevent Unpoly from changing any element. Your event handler can then restore the page with your own custom code:

up.on('up:location:restore', function(event) {
  // Stop Unpoly from rendering anything
  event.preventDefault()
  
  // We will render ourselves
  document.body.innerText = `Restored content for ${event.location}!`
})

When up:location:restore is emitted, the browser location has already been updated. This cannot be prevented by an event listener.

Important

Custom restoration code should not push new history entries.

Handled history entries

By default Unpoly feels responsible for handling history entries that it owns:

  • The entry of the initial page load, after Unpoly has booted.
  • Locations changed by Unpoly while navigating or rendering with { history: true }.
  • Entries pushed by changing the #hash of a location that Unpoly owns

You can control whether Unpoly will handle a location change by listening to up:location:changed and mutating the event.willHandle property.

History restoration with overlays

See History restoration with overlays.