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

JavaScript如何获取重定向到当前页面的完整来源Referrer URL

问题原因

document.referrer仅返回域名是站点默认的Referrer Policy限制导致,默认配置下重定向场景仅会传递源站域名,不会传递完整路径。

可行解决方案

方案1:重定向携带来源参数(最稳定,兼容性最好)

该方案不受浏览器策略限制,适配服务端重定向、前端跳转等所有场景:

  • 跳转时在目标url后拼接编码后的来源地址参数:
    服务端3xx重定向(以NGINX为例):
    rewrite ^/content.html$ https://example.com/news.html?from=$request_uri permanent;
    rewrite ^/files/actual.html$ https://example.com/news.html?from=$request_uri permanent;
    
    前端跳转:
    window.location.href = `https://example.com/news.html?from=${encodeURIComponent(window.location.href)}`
    
  • 在news.html中提取参数作为返回地址:
    function getQueryParam(name) {
      const urlParams = new URLSearchParams(window.location.search);
      return urlParams.get(name) ? decodeURIComponent(urlParams.get(name)) : '/';
    }
    const referrerUrl = getQueryParam('from');
    // 绑定返回按钮事件
    document.querySelector('#back-btn').addEventListener('click', () => {
      window.location.href = referrerUrl;
    })
    

方案2:调整Referrer Policy(仅适合同站场景)

在全站所有页面的<head>标签内添加如下配置,允许同站场景传递完整Referrer路径:

<meta name="referrer" content="same-origin">

配置完成后,直接使用document.referrer即可拿到完整的同站来源路径。

方案3:使用sessionStorage存储来源

如果不想修改URL和全局策略,可以在跳转前本地存储来源地址:

// 所有跳转到news.html的页面,跳转前执行
sessionStorage.setItem('news_prev_url', window.location.href);

// news.html页面读取
const referrerUrl = sessionStorage.getItem('news_prev_url') || '/';
// 读取后可清除避免复用
sessionStorage.removeItem('news_prev_url');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:39:00