如何获取document.referrer的上级来源?JavaScript代码问题求助
获取来源页的来源地址解决方案
document.referrer 是只读字符串,仅能返回当前页面的直接来源URL,不存在 .referrer 嵌套属性,所以你的 nftStatistics 函数会因非法属性调用报错。以下是两种可行的解决办法:
方案一:URL参数传递上级来源
在从来源页跳转到中间页(比如你提到的设置页)时,主动把来源页的referrer通过URL参数传递过去。
比如在来源页跳转时执行:
// 跳转时携带来源页的referrer作为参数 window.location.href = '/path/to/settings-page.html?from=' + encodeURIComponent(document.referrer);
然后在中间页的nftStatistics函数中读取该参数:
function nftStatistics() { if(window.location.href.indexOf("statistics") > -1 && history.length) { history.go(-2); } else if(window.location.href.indexOf("games") > -1 && history.length) { const urlParams = new URLSearchParams(window.location.search); // 优先取URL参数里的上级来源,没有则用当前页的referrer兜底 const grandparentReferrer = urlParams.get('from') || document.referrer; window.location.replace(grandparentReferrer + "/../tournament.html"); } else { window.location.replace("./tournaments/tournament.html"); } }
方案二:sessionStorage记录访问轨迹
在所有页面加载时,把当前页面的来源和URL存入sessionStorage,维护一个访问历史栈,后续可以从中回溯上级来源。
在全局通用脚本中添加:
window.addEventListener('load', () => { let visitHistory = JSON.parse(sessionStorage.getItem('visitHistory')) || []; // 记录当前页面的URL和来源 visitHistory.push({ url: window.location.href, referrer: document.referrer }); // 限制栈长度,避免存储过载 if (visitHistory.length > 5) visitHistory.shift(); sessionStorage.setItem('visitHistory', JSON.stringify(visitHistory)); });
修改后的nftStatistics函数:
function nftStatistics() { if(window.location.href.indexOf("statistics") > -1 && history.length) { history.go(-2); } else if(window.location.href.indexOf("games") > -1 && history.length) { const visitHistory = JSON.parse(sessionStorage.getItem('visitHistory')) || []; const currentPageIndex = visitHistory.findIndex(item => item.url === window.location.href); let grandparentReferrer = document.referrer; // 如果能找到当前页在历史栈中的位置,取前一页的referrer if (currentPageIndex > 0) { grandparentReferrer = visitHistory[currentPageIndex - 1].referrer || grandparentReferrer; } window.location.replace(grandparentReferrer + "/../tournament.html"); } else { window.location.replace("./tournaments/tournament.html"); } }
方案对比
- URL参数方案:可靠性高,不受浏览器存储清理影响,但需要在跳转环节主动修改传递逻辑。
- sessionStorage方案:无需修改跳转逻辑,但用户清空存储或打开新标签页时,历史轨迹会丢失。
内容的提问来源于stack exchange,提问作者Sakura Queen
相关产品推荐
相关产品推荐

