document.referrer 可獲取導流來源頁面 URL,是流量分析、廣告追蹤的關鍵依據。但多種情況會導致 referrer 遺失或不準,需了解成因並採取補救措施。
| 場景 | IE | Chrome/Firefox/Safari/Opera | 說明 |
|---|---|---|---|
| location.href / location.assign 導航 | 遺失 | 正常 | IE 視為同一文檔導航 |
| window.open 新視窗 | 遺失 | 正常 | IE 不傳遞 referrer |
| 滑鼠拖曳連結開啟 | 遺失 | 遺失 | 多數瀏覽器視為用戶主動操作 |
| Flash 內部連結點擊 | 遺失/指向 SWF | 不一 | Chrome 指向 SWF,Firefox/Opera 正常 |
| HTTPS → HTTP 跳轉 | 遺失 | 遺失 | 瀏覽器安全策略,不降級傳遞 referrer |
function gotoUrl(url) {
if (window.VBArray) { // 判斷 IE
var a = document.createElement('a');
a.href = url;
document.body.appendChild(a);
a.click(); // 模擬點擊 ,保留 referrer
} else {
window.location.href = url;
}
}
var referrer = document.referrer;
if (!referrer) {
try {
if (window.opener && window.opener.location.href) {
referrer = window.opener.location.href; // 同域才可存取
}
} catch(e) { /* 跨域拋錯 */ }
}
<a href="..." rel="noreferrer">(Chrome 4+、Firefox、Edge 支援)。window.open('javascript:location.replace("target.html")'),新視窗無 referrer。<meta http-equiv="refresh" content="0;url=target.html"> 通常不傳遞 referrer。?utm_source=google&utm_medium=cpc&utm_campaign=summer,不依賴 referrer。URLSearchParams 取出 utm_*/gclid 送入分析系統。伺服器可透過 Referrer-Policy 標頭控制瀏覽器發送策略:
Referrer-Policy: strict-origin-when-cross-origin // 預設
Referrer-Policy: no-referrer // 完全不送
Referrer-Policy: origin // 僅送 origin
Referrer-Policy: unsafe-url // 完整 URL(含 query),跨域也送
也可在頁面設定:<meta name="referrer" content="no-referrer">。