履歴に新しい状態(state)と URL を追加。ページ遷移せず URL を変更できる。
history.pushState(state, title, url)
使用例
// URL を更新(ページ遷移なし)
const newURL = `/search?query=${encodeURIComponent(query)}`;
history.pushState({ query }, "", newURL);
//プロパティ名と変数名が同じなので省略{ query: query }
// ブラウザ戻る/進む対応
window.addEventListener("popstate", (e) => {
const query = e.state?.query || "";
input.value = query;
if (query) performSearch(query);
else results.innerHTML = "";
});
「戻る」ボタンで前の検索語を復元して再検索
ページ遷移せず、ユーザーにシームレスな体験を提供
pushStateとpopstateはほぼセットで使われる
stateはオブジェクトで渡せる
const query = "apple";
const category = "fruit";
const page = 2;
const newURL = `/search?query=${encodeURIComponent(query)}&category=${encodeURIComponent(category)}&page=${page}`;
history.pushState({ query, category, page }, "", newURL);
window.addEventListener("popstate", (e) => {
console.log(e.state.query); // "apple"
console.log(e.state.category); // "fruit"
console.log(e.state.page); // 2
});