ヒストリ(History)
目次
戻ると進む
window.history
ひとつ前に見ていたページ、ふたつ前に見ていたページなどの、ウィンドウのヒストリ情報を保持、制御するオブジェクトです。
window.history.length
ヒストリの個数を返します。
window.history.current
window.history.next
window.history.previous
ヒストリ上の、現在の(current)、次の(next)、前の(previous)アドレス(URL)を示す文字列を返します。
window.history.back()
window.history.forward()
window.history.go(n)
back() はひとつ前のページに、forward() はひとつ先のページに、go(n) は n 個先のページにジャンプします。n に負数を指定すると n 個前のページに戻ります。
HTML
<a href="#" onclick="history.back(); return false;">[戻る]</a>
ヒストリ操作
window.history.pushState(state, unused[, url])
window.history.replaceState(state, unused[, url])
window.history.state
pushState() はヒストリに指定した URL を追加します。replaceState() はヒストリの最新のエントリを URL に置き換えます。第二引数は現在は使用されません。ブラウザの進む・戻るボタンでヒストリを移動した際 popstate イベントが発生し、イベントハンドラの延長で history.state を参照することができます。history.state には pushState() や replaceState() の state で指定した任意のオブジェクト情報を受け取ることができます。
これらの機能は、SPA(Single Page Application) において疑似的にページ遷移を行う際、ヒストリで進む・戻るを実現する際に役立ちます。下記は、JavaScript を用いて疑似的に Page1 → Page2 → Page3 と遷移し、pushState() や history.state を用いて疑似的にヒストリ遷移を可能とするサンプルです。
HTML
<!doctype html> <html lang="ja"> <head> <title>TEST</title> <style> .page { display: none; } .show { display: block; } </style> </head> <body> <div class="page" id="page1"> <h1>Page1</h1> <button onclick="goPage('page2')">Page2</button> </div> <div class="page" id="page2"> <h1>Page2</h1> <button onclick="goPage('page3')">Page3</button> </div> <div class="page" id="page3"> <h1>Page3</h1> <button onclick="goPage('page2')">Page2</button> </div> <script> (function() { goPage("page1"); })(); function goPage(page) { document.querySelectorAll(".page").forEach((e) => { e.classList.remove("show") }); document.querySelector("#" + page).classList.add("show"); history.pushState({"page": page}, null, page); } window.onpopstate = function(e) { document.querySelectorAll(".page").forEach((e) => { e.classList.remove("show") }); document.querySelector("#" + history.state.page).classList.add("show"); } </script> </body> </html>
Copyright (C) 1996-2002 杜甫々
改訂版初版:2022年6月5日、最終更新:2022年6月5日
https://www.tohoho-web.com/js/history.htm