在做流量統計或來源分流時,有時需要判斷訪客是從哪個網站點擊而來,例如判斷來源是否來自百度等搜尋引擎,再決定後續行為。這可以透過 document.referrer 取得來源網址來實現。
需要留意的是,直接彈出視窗的方式容易被瀏覽器或安全軟體攔截,而使用 self.location 進行頁內導向則相對單純。以下示範透過表單提交的方式來觸發導向:
<script type="text/javascript"> $(function(){ var s=document.referrer; //獲取來源地址 if(s.indexOf("baidu")>0) //來源是否有baidu出現 //self.location="https://www.baidu.com/";//原窗口 document.getElementById('openWin').submit(); document.getElementById('openWin2').submit(); //window.open("https://www.taobao.com") //window.open("https://www.360.com") }); </script> <form id="openWin" action="https://www.taobao.com" target="_blank" method="get"></form> <form id="openWin2" action="https://www.360.com" target="_blank" method="get"></form>這段程式先讀取 document.referrer,判斷來源網址中是否包含特定關鍵字,再決定要提交的表單或要導向的位置。實際應用時,請務必依使用者意願與相關規範謹慎使用,避免造成不好的瀏覽體驗。以上就是這次的實作分享,希望對大家有所幫助。