Others

Swup の updateHistoryRecord ヘルパー関数を使って URL を更新する

March 20, 2025

Swup を使っているプロジェクトでは、History API の window.history.replaceState() などを使って直接 URL を更新すると、 swup との連携がうまくいかなくなる。

このようなケースでは、用意されているヘルパー関数 updateHistoryRecord() を使う。

import { updateHistoryRecord } from 'swup'
 
// ...
 
const newUrl = new URL(window.location.href)
newUrl.searchParams.set('show', currentCount.toString())
updateHistoryRecord(newUrl.toString())

ちなみに、updateHistoryRecord.ts の実装は次のようになっている。

swup/src/helpers/updateHistoryRecord.ts
/** Update the current history record with a custom swup identifier. */
export const updateHistoryRecord = (
  url: string | null = null,
  data: HistoryData = {}
): void => {
  url = url || getCurrentUrl({ hash: true })
  const currentState = (window.history.state as HistoryState) || {}
  const state: HistoryState = {
    ...currentState,
    url,
    random: Math.random(),
    source: 'swup',
    ...data,
  }
  window.history.replaceState(state, '', url)
}

back to note