想知道使用者是從哪裡點進來的,用 document.referrer。它回傳上一頁的完整網址,若沒有來源(直接輸入網址、從書籤開啟,或來源使用了 rel="noreferrer")則是空字串。
<!DOCTYPE html> <html> <body> The referrer of this document is: <script> document.write(document.referrer); </script> </body> </html>
判斷是否為外部來源。
function isExternalReferrer() {
if (!document.referrer) return false; // 沒有來源,無法判斷
return document.referrer.indexOf(location.origin) !== 0;
}
取得來源網域。
var host = document.referrer ? new URL(document.referrer).hostname : "(direct)";
實作「返回上一頁」。直接呼叫 history.back() 有風險:使用者可能是從外部網站進來的,一按就離開你的站。比較穩妥的做法是看 referrer:
function goBack() {
if (document.referrer && document.referrer.indexOf(location.origin) === 0) {
history.back();
} else {
location.href = "/";
}
}
它只反映「文件載入那一刻」的來源。用 history.pushState 做的前端路由跳轉不會更新 document.referrer,它不會變成你的上一個 SPA 頁面。要在 SPA 裡追蹤頁內導覽,得自己維護。
可能被瀏覽器或網站刻意隱藏。從 HTTPS 頁面連到 HTTP 頁面時,referrer 會被丟掉。來源網站若設了 Referrer-Policy: no-referrer,或用 rel="noreferrer" 的連結,你這邊收到的就是空字串。所以「referrer 為空」不代表使用者直接輸入網址。
它是伺服器端也能拿到的資訊。HTTP 請求標頭中的 Referer(拼寫是歷史錯誤,少一個 r)與 document.referrer 是同一份資料。做統計時以伺服器日誌為準會比前端可靠,因為 JS 可能沒執行到。
另外提醒隱私面的考量:referrer 網址可能帶有查詢字串,其中包含搜尋關鍵字、頁碼,甚至權杖。若你的頁面會被當成別人的來源,記得用 <meta name="referrer" content="strict-origin-when-cross-origin"> 控制要洩漏多少,別把完整網址連同參數一起送出去。