You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js应用中浏览器返回按钮自动滚动至顶部的禁用方法

禁用Next.js中浏览器返回时的自动滚动行为

Pages Router(Next.js 12及更早)

Next.js默认会在路由切换(包括浏览器返回)时自动管理滚动位置。要完全禁用该行为,可在_app.js/_app.tsx中通过路由事件和beforePopState钩子控制:

import { useEffect } from 'react';
import { useRouter } from 'next/router';

function MyApp({ Component, pageProps }) {
  const router = useRouter();

  useEffect(() => {
    // 拦截返回导航,阻止Next.js默认的滚动恢复逻辑
    router.beforePopState(() => true);

    // 移除路由切换完成后的自动滚动到顶部行为
    const removeScrollHandler = () => {
      // 注释掉下面这行,就不会在路由切换时自动滚到顶部
      // window.scrollTo(0, 0);
    };

    router.events.on('routeChangeComplete', removeScrollHandler);
    return () => router.events.off('routeChangeComplete', removeScrollHandler);
  }, [router]);

  return <Component {...pageProps} />;
}

export default MyApp;

App Router(Next.js 13+)

在App Router模式下,滚动行为由框架默认管理,可通过以下两种方式禁用:

方式1:根Layout设置手动滚动恢复

直接在根layout.js/layout.tsx的<html>标签上添加scrollRestoration="manual",让浏览器和Next.js都停止自动滚动管理:

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN" scrollRestoration="manual">
      <body>{children}</body>
    </html>
  );
}

方式2:自定义路由滚动逻辑(按需控制)

如果需要更精细的控制,可在客户端组件中监听路由变化,完全取消自动滚动:

'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';

export default function RootLayout({ children }) {
  const pathname = usePathname();

  useEffect(() => {
    // 路由切换时不执行任何自动滚动操作,注释掉下面一行即可
    // window.scrollTo(0, 0);
  }, [pathname]);

  return (
    <html lang="zh-CN">
      <body>{children}</body>
    </html>
  );
}

针对返回按钮的单独处理

如果只想禁用浏览器返回时的自动滚动,而保留其他路由切换的滚动行为,可直接监听popstate事件:

useEffect(() => {
  const handlePopState = (e) => {
    // 阻止浏览器默认的返回滚动恢复
    e.preventDefault();
  };

  window.addEventListener('popstate', handlePopState);
  return () => window.removeEventListener('popstate', handlePopState);
}, []);

内容的提问来源于stack exchange,提问作者Mo J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 17:20:56