LoginSignup
4
4

More than 5 years have passed since last update.

HistoryAPIの使い方

Last updated at Posted at 2017-12-21

必要なメソッドは以下の三種

  • pushState(state, title, url)
  • replaceState(state, title, url)
  • onpopstate(function(e))

pushState

ブラウザの履歴を追加する

第一引数にjavascriptオブジェクトを自由に入れることができる
第二引数は現在使われていないためnullで良い
第三引数には変更したいurlを入れる

replaceState

現在のブラウザの履歴を更新する

第一引数にjavascriptオブジェクトを自由に入れることができる
第二引数は現在使われていないためnullで良い
第三引数には変更したいurlを入れる

pushStateとreplaceStateの違い

例えば localhost:3000/home.htmlという場所をスタートとした場合

// pushStateの場合
pushState(null, null, 'localhost:3000/company.html')
// 履歴の中身 ['localhost:3000/home.html', 'localhost:3000/company.html']
// 戻るボタンを押すとlocalhost:3000/home.htmlに戻る

// replaceStateの場合
replaceState(null, null, 'localhost:3000/company.html')
// 履歴の中身 ['localhost:3000/company.html']
// 戻るボタンを押すとlocalhost:3000/company.htmlよりも前にいたページに戻る

というような違いが現れる

popState

ブラウザの戻るボタンを押したときに発生する(pushStateで入れた履歴の場合のみ)

  • サンプル
$(window).on('popstate', function(event) {
  // 処理
})
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4