多页面网站中如何获取用户首次访问的原始入口URL?
如何获取用户首次访问的原始URL?
核心结论
浏览器不能直接轻松获取用户的首次访问原始URL——默认情况下,浏览器仅提供document.referrer(记录当前页面的直接跳转来源),但它只会保存上一页的地址,而非用户进入网站的第一个完整URL。要获取首次访问的原始URL,需要主动存储这个信息。
可行解决方案
1. 用Cookie存储首次访问URL
当用户第一次进入网站时,检查是否已有存储首次URL的Cookie;如果没有,就把当前页面的完整URL(包括utm参数)存进去,后续页面直接读取这个Cookie即可。
示例代码:
// 页面加载时执行 window.addEventListener('load', function() { // 检查是否已存储首次访问URL if (!document.cookie.includes('firstVisitUrl')) { // 保存当前完整URL到Cookie,有效期设为1天(可按需调整) const expires = new Date(); expires.setTime(expires.getTime() + (24 * 60 * 60 * 1000)); document.cookie = `firstVisitUrl=${encodeURIComponent(window.location.href)}; expires=${expires.toUTCString()}; path=/`; } // 在/page-b等页面读取首次URL const firstUrlMatch = document.cookie.match(/firstVisitUrl=([^;]+)/); if (firstUrlMatch) { const firstUrl = decodeURIComponent(firstUrlMatch[1]); console.log('首次访问URL:', firstUrl); } });
2. 用LocalStorage/SessionStorage存储
逻辑和Cookie类似,只是存储位置换成浏览器的本地存储,适合不需要和服务器交互的场景:
示例代码:
window.addEventListener('load', function() { if (!localStorage.getItem('firstVisitUrl')) { localStorage.setItem('firstVisitUrl', window.location.href); } const firstUrl = localStorage.getItem('firstVisitUrl'); console.log('首次访问URL:', firstUrl); });
注意:SessionStorage会在浏览器关闭后失效,LocalStorage会长期保存,可根据需求选择。
3. 服务器端会话存储
如果你的网站有服务器端会话支持(比如PHP、Node.js等),可以在用户首次请求时,把原始URL存入会话,后续页面从会话中读取:
PHP示例:
// 初始化会话 session_start(); // 首次请求时记录原始URL if (!isset($_SESSION['firstVisitUrl'])) { $_SESSION['firstVisitUrl'] = "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; } // 在其他页面获取首次访问URL echo '首次访问URL: ' . $_SESSION['firstVisitUrl'];
注意事项
- 可以通过判断
document.referrer是否为非本站域名,优化存储逻辑,确保只有用户从外部进入网站时才记录首次URL,避免站内跳转时覆盖。 - 存储URL时记得用
encodeURIComponent编码,避免特殊字符导致存储异常。
内容的提问来源于stack exchange,提问作者Xin
相关产品推荐
相关产品推荐

