Open4

History: pushState() メソッド

hoshitahoshita
  • ブラウザのセッション履歴スタックに項目を追加できる
hoshitahoshita

使用した場面

window.location.href = '/hoge/foo'

であれば、/hoge/fooに居たとしても画面の再読み込みが走る

しかし

window.location.href = '/hoge/foo#bar'

だと/hoge/fooもしくは/hoge/foo/#barにいた場合、画面の再読み込みが走らない

ここで走らせたい時に、window.location.reload();と合わせて使用することで画面の再読み込みが可能になる。

history.pushState(null, '', '/hoge/foo#bar');
window.location.reload();
hoshitahoshita

ブラウザバックをすると挙動がおかしくなる

現在のパスを見て、必要な箇所でhistory.pushStateを使用し、それ以外のところではwindow.location.hrefを使用する方が安全

if (window.location.pathname === '/hoge/foo') {
    history.pushState(null, '', '/hoge/foo#bar');
    window.location.reload();
} else {
    window.location.href = '/hoge/foo#bar';
}