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

如何在JavaScript及Next.js项目中获取前一页URL地址?

Next.js获取前一页URL的正确解法

你之前的方案失效原因

  • document.referrer仅在整页加载、跨站点跳转时会更新,Next.js客户端路由属于单页内路由切换,不会触发浏览器更新该字段,因此只会返回首次进入站点的根地址。
  • 直接调用原生history.pushState存储状态会被Next.js封装的路由层覆盖:Next.js的<Link>、router.push等路由API跳转时会自行操作历史栈,你手动存入的自定义状态会被冲刷掉,因此目标页无法读取。

可用解法

解法1:使用Next.js路由内置state传参(适合单次跳转传递来源)

无需全局配置,仅需在跳转时传入参数即可。

Pages Router 写法

来源页跳转逻辑:

import { useRouter } from 'next/router'
import Link from 'next/link'

const SourcePage = () => {
  const router = useRouter()
  // 函数式跳转
  const handleJump = () => {
    router.push({
      pathname: '/target',
      state: { prevPath: router.asPath }
    })
  }

  return (
    <>
      <button onClick={handleJump}>函数跳转</button>
      {/* Link组件跳转 */}
      <Link href={{
        pathname: '/target',
        state: { prevPath: router.asPath }
      }}>
        Link跳转
      </Link>
    </>
  )
}

目标页取值:

import { useRouter } from 'next/router'

const TargetPage = () => {
  const router = useRouter()
  const prevPath = router.state?.prevPath
  return <div>来源页:{prevPath}</div>
}

App Router 写法

来源页跳转逻辑:

'use client'
import { useRouter } from 'next/navigation'
import Link from 'next/link'

const SourcePage = () => {
  const router = useRouter()
  const currentPath = window.location.pathname

  // 函数式跳转
  const handleJump = () => {
    router.push('/target', { state: { prevPath: currentPath } })
  }

  return (
    <>
      <button onClick={handleJump}>函数跳转</button>
      {/* Link组件跳转 */}
      <Link href="/target" state={{ prevPath: currentPath }}>
        Link跳转
      </Link>
    </>
  )
}

目标页取值:

'use client'
const TargetPage = () => {
  // 需在客户端组件内调用,避免服务端渲染报错
  const prevPath = typeof window !== 'undefined' ? window.history.state?.prevPath : null
  return <div>来源页:{prevPath}</div>
}

注意:该方案存储的状态会在用户刷新目标页后丢失,需要持久化存储请用解法2


解法2:全局存储上一路径(支持页面刷新后读取)

通过监听路由变更,将上一页路径存入sessionStorage,全局任意页面都可读取,刷新页面不会丢失。

Pages Router 配置

在_app.js中添加路由监听:

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

export default function App({ Component, pageProps }) {
  const router = useRouter()

  useEffect(() => {
    const savePrevPath = () => {
      sessionStorage.setItem('prevPath', router.asPath)
    }
    // 路由开始变更时存储当前路径为下一页的前一页路径
    router.events.on('routeChangeStart', savePrevPath)
    return () => router.events.off('routeChangeStart', savePrevPath)
  }, [router])

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

App Router 配置

在根layout.js中添加路由监听:

'use client'
import { usePathname } from 'next/navigation'
import { useEffect } from 'react'

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

  useEffect(() => {
    // 路径变化时存储上一次路径
    const prevPath = sessionStorage.getItem('currentPath')
    if (prevPath) sessionStorage.setItem('prevPath', prevPath)
    sessionStorage.setItem('currentPath', pathname)
  }, [pathname])

  return <html><body>{children}</body></html>
}

任意页面取值:

const prevPath = typeof window !== 'undefined' ? sessionStorage.getItem('prevPath') : null

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:45:03