7
7

More than 3 years have passed since last update.

【Nuxt.js】iOSでブラウザバックした時、元のスクロール位置に戻らない

Last updated at Posted at 2020-11-05

(もっといい方法があれば教えて下さい!!🙇)

概要

Nuxt.jsプロジェクトで、外部ページに遷移してブラウザバックをしたところ、
画面最上部に戻されてしまったので対策。

結論

ホームディレクトリにapp/router.scrollBehavior.jsを追加し、下記のコードを実装

app/router.scrollBehavior.js
if (process.client) {
  if ('scrollRestoration' in window.history) {
    window.addEventListener('load', () => {
      window.history.scrollRestoration = 'auto'
    })
  }
}

理由

スクロール位置の復元設定が既存のrouter.scrollBehavior.jsで実装されているが、
iosだとbeforeunloadが発火しない。
なので、window.history.scrollRestorationがautoに設定されず、
window.history.scrollRestorationがmanualに設定されているので、ブラウザバック時に画面最上部に戻される。

対策として、常にwindow.history.scrollRestoration = autoになるように実装

node_modules/@nuxt/vue-app/template/router.scrollBehavior.js
// 7行目〜23行目
if (process.client) {
  if ('scrollRestoration' in window.history) {
    window.history.scrollRestoration = 'manual'

    // reset scrollRestoration to auto when leaving page, allowing page reload
    // and back-navigation from other pages to use the browser to restore the
    // scrolling position.
    window.addEventListener('beforeunload', () => {
      window.history.scrollRestoration = 'auto'
    })

    // Setting scrollRestoration to manual again when returning to this page.
    window.addEventListener('load', () => {
      window.history.scrollRestoration = 'manual'
    })
  }
}

参考

クロール位置の復元
beforeunloadはiOSで効かない
scrollBehavior

7
7
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
7
7