質問
history.scrollrestoration の設定はセッション履歴エントリ(session history entries)に保存されるため、
一度'manual'に設定すると戻る・進むでページを遷移しても設定は変わらないと思うのですが、
実際には'manual'に設定後にページを戻った場合はスクロール位置が復元されて、
historyにはデフォルトの'auto'が設定されています。
これはどういうことでしょうか?
ページ遷移時にはhistory.scrollrestorationは引き継がれず必ずデフォルトの'auto'が設定される仕様なのでしょうか?
根拠となる記述があるサイトなどがあれば教えていただけますと幸いです。
再現
- index.html を開く(このページでは history.scrollRestoration はデフォルトの 'auto')。
- index.html で一番下にスクロールして位置を変える。
- index.html から page2.html に遷移する(このページでJavaScriptを使って history.scrollRestoration を 'manual' に設定)。
- page2.html からブラウザの「戻る」ボタンを使って index.html に戻る。
- この時点で index.html のスクロール位置が復元される。(history.scrollRestorationは'auto'に設定されている)。
※ index.htmlでもscript.jsを読み込むと5でスクロール位置が復元されなくなる
※ Chrome, safari, firefox で同じ挙動になることを確認
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page 1</title>
</head>
<body>
<h1>This is Page 1</h1>
<div style="height: 2000px;">
</div>
<a href="page2.html">Go to Page 2</a>
</body>
</html>
page2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js" defer></script>
<title>Page 2</title>
</head>
<body>
<h1>This is Page 2</h1>
</body>
</html>
script.js
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}