当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。