【react】获取上一页路径

随笔1个月前发布
19 0 0

作用:

1,埋点记录来源

2,根据来源区分业务场景(区分首页 详情页 进入列表的滚动记录)

常规场景可以通过document.referrer拿到,但spa应用中切换路由document.referrer不会改变。

查看了react-router和history的API,都没有提供监听路由变化的函数。因此采取的方案是,添加一个生命周期钩子,在location.pathname改变时,将旧的url保存在全局变量中。

// util.js

export const setReferrerUrl = (prevPath) => {

  window.referrerUrl = window.referrerUrl ? `${window.location.origin}${prevPath}` : document.referrer

}

// layout.js
import React, { useState, useEffect, useRef } from 'react'
import { Link, useHistory } from 'react-router-dom'

const history = useHistory()
// router v6  const history = useLocation()
// ...
/** TODO: 收集埋点需要的上一页路径 */
  const usePrevious = (value) => {
    const ref = useRef()
    useEffect(() => {
      ref.current = value
    })
    return ref.current
  }
  const prevPath = usePrevious(history.location.pathname)
  useEffect(() => {
    setReferrerUrl(prevPath)
  }, [history.location.pathname])

下面的场景无法获得 referrer 信息:

1、直接在浏览器中输入地址
2、使用location.reload()刷新(location.href或者location.replace()刷新有信息)
3、在微信对话框中,点击进入微信自身浏览器 扫码进入微信或QQ的浏览器
直接新窗口打开一个页面
4、a标签设置rel=”noreferrer”(兼容IE7+)
5、meta标签来控制不让浏览器发送referer
6、Chrome4.0以下,IE 5.5+以下返回空的字符串
7、使用 修改 Location 进行页面导航的方法,会导致在IE下丢失 referrer,这可能是IE的一个BUG

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...