當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


HTML DOM referrer用法及代碼示例

HTML中的DOM Referrer屬性用於返回鏈接到當前頁麵的頁麵的URI。如果用戶直接或通過書簽導航到頁麵,則此值為空字符串。

用法:

document.referrer

以下示例程序旨在說明HTML中的Referrer屬性:


例:有3個頁麵相互鏈接,並在下麵指定其Referrer屬性。

page1.html

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>Referrer Property</title> 
</head> 
  
<body> 
    <h1 style="color:green;">GeeksForGeeks</h1> 
    <h2>Page 1</h2> 
    <p>Click on the below links to go to the other pages</p> 
    <a href="page2.html">Go to Page 2</a> 
    <a href="page3.html">Go to Page 3</a> 
    <p> 
        <b>You are referred to this page by:</b> 
    </p> 
    <div class="referrer"></div> 
    <script> 
        // access the referrer property 
        let referrer = document.referrer; 
  
        // replace div with the referrer link 
        document.querySelector('.referrer').innerHTML =  
            referrer; 
    </script> 
  
</body> 
  
</html>

page2.html

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>Referrer Property</title> 
</head> 
  
<body> 
    <h1 style="color:green;">GeeksForGeeks</h1> 
    <h2>Page 2</h2> 
    <p>Click on the below links to go to the other pages</p> 
    <a href="page1.html">Go to Page 1</a> 
    <a href="page3.html">Go to Page 3</a> 
    <p> 
        <b>You are referred to this page by:</b> 
    </p> 
    <div class="referrer"></div> 
    <script> 
        // access the referrer property 
        let referrer = document.referrer; 
  
        // replace div with the referrer link 
        document.querySelector('.referrer').innerHTML =  
            referrer; 
    </script> 
  
</body> 
  
</html>

page3.html

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>Referrer Property</title> 
</head> 
  
<body> 
    <h1 style="color:green;">GeeksForGeeks</h1> 
    <h2>Page 3</h2> 
    <p>Click on the below links to go to the other pages</p> 
    <a href="page1.html">Go to Page 1</a> 
    <a href="page2.html">Go to Page 2</a> 
    <p> 
        <b>You are referred to this page by:</b> 
    </p> 
    <div class="referrer"></div> 
    <script> 
        // access the referrer property 
        let referrer = document.referrer; 
  
        // replace div with the referrer link 
        document.querySelector('.referrer').innerHTML =  
            referrer; 
    </script> 
  
</body> 
  
</html>

輸出#1

導航到第一頁。返回的字符串為空,因為我們直接打開了此頁麵。

Directly navigating to first page

輸出#2

點擊後'第2頁'第1頁的鏈接。

After Clicking 2 from 1

輸出#3

點擊後“第3頁”第2頁的鏈接。

After Clicking 3 from 2

支持的瀏覽器:DOM Referrer屬性支持的瀏覽器如下:

  • Chrome
  • IE瀏覽器
  • Firefox
  • Opera
  • Safari


相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 HTML | DOM referrer Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。