How to Get Document Referrer in JavaScript
This article will present how to get a document referrer programmatically during webpage execution using JavaScript events and functions with different examples.
Document Referrer
The referrer is a DOM read-only property that returns the URL of the document linked with our current webpage. As we have arrived at the current webpage, we might click a link or any button to navigate.
To get access to a website or any webpage from a client-side application, we must require the URL or path of the document. It is the location of a particular website, web page, or file uploaded to a server.
A string users type into a web browser search to invoke and call a specific website is a website URL.
For example, https://www.delftstack.com/
is the complete URL for DelftStack with application layer protocol (HTTP).
Property Syntax:
document.referrer; // it will get us complete web URL with (HTTPS) like
// (https://www.delftstack.com/)
Suppose we are developing a website or a web page. And for some circumstances, we need to find out and use the current document referrer programmatically during the website’s run time.
We can deal with it using JavaScript. It can be useful when maintaining custom back navigations.
Get Document Referrer in JavaScript
In HTML, the DOM referrer property is read-only, used within JavaScript source to get the URL of the HTML document or web page linked to the current web page. The return value of this property can be an empty string if the user directly accesses the page through the bookmark.
Including the network layer protocol (HTTPS), we can get the entire URL by using the DOM referrer property.
Basic Syntax:
let refURL = document.referrer
Example code:
<!DOCTYPE html>
<html>
<body>
<h1>DelftStack learning</h1>
<h2>JavaScript get document referrer example</h2>
<p>We have arrived from this link : </p>
<p id="para"></p>
<script>
let refUrl = document.referrer // get referrer and storing in variable
document.getElementById("demo").innerHTML = refUrl; // assign value to paragraph
</script>
</body>
</html>
Example code explanation:
- In the above HTML source code, we have used the paragraph element tag
<p></p>
and assigned an ID to that element. - Inside the
<script></script>
tags we have declared and initialized therefUrl
variable. - Now, to get the document URL, we have used the
document.referrer
property and stored the return value in a variable. - Finally, with the help of the
document.getElementById()
method, we have displayed the result string in the paragraph. - You can save the above source with a
.html
extension and see the result.