html | 浏览器滚动恢复属性History.scrollRestoration

Posted by KazooTTT on November 27, 2022

最近在阅读React新版官网的代码时,发现在_app.tsx中有这样一段代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
useEffect(() => {
  // Taken from StackOverflow. Trying to detect both Safari desktop and mobile.
  const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  if (isSafari) {
    // This is kind of a lie.
    // We still rely on the manual Next.js scrollRestoration logic.
    // However, we *also* don't want Safari grey screen during the back swipe gesture.
    // Seems like it doesn't hurt to enable auto restore *and* Next.js logic at the same time.
    history.scrollRestoration = 'auto';
  } else {
    // For other browsers, let Next.js set scrollRestoration to 'manual'.
    // It seems to work better for Chrome and Firefox which don't animate the back swipe.
  }
}, []);

这里用到了我没有接触过的一个属性History.scrollRestoration,发现这个属性是用来控制页面刷新或者返回后是否滚动到原来的位置。

MDN文档

属性的值:

  1. auto 将恢复用户已滚动到的页面上的位置。
  2. manual 未还原页上的位置。用户必须手动滚动到该位置。

在mdn文档中没有看到auto是默认值,但是自己手动验证以及在google blog 中提到:

The good news is, however, that there’s a potential fix: history.scrollRestoration. It takes two string values: auto, which keeps everything as it is today (and is its default value), and manual, which means that you as the developer will take ownership of any scroll changes that may be required when a user traverses the app’s history.

所以auto确实是默认值没错。

举例

  1. 如果history.scrollRestoration = ‘auto’; 自动回到原有位置。

  2. 如果history.scrollRestoration = ‘manual’; 回到顶部。

在react.org/beta(新版官网)中为什么要使用manul

这是因为这个项目用的next.js,涉及到ssr,可能出现页面还没渲染完就滚动到了之前的位置。(待补充例子。) 可以看一下这篇文档Next.js 中怎么保持页面的滚动位置