We can get the previous page URL in JavaScript with the document.referrer
property.
For example:
const previousPageUrl = document.referrer;
console.log(`Previously visited page URL: ${previousPageUrl}`);
document.referrer
is a readonly property that returns the URL of the page used to navigate to the current page.
Here’s a more practical example:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Coding Beauty Tutorial</title>
</head>
<body>
<a href="get-last-page.html">Link</a>
</body>
</html>
get-last-page.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Coding Beauty Tutorial</title>
</head>
<body>
You visited this page from: <span id="previous-page"></span>
<script src="get-last-page.js"></script>
</body>
</html>
get-last-page.js
const previousPage = document.getElementById('previous-page');
previousPage.textContent = document.referrer;
Limitations of document.referrer
The document.referrer
property doesn’t always work though. It typically gives the correct value in cases where the user clicked a link on the previous page to navigate to the current page.
But if the user visited the URL directly by typing into the address bar or using a bookmark, document.referrer
will have no value.
document.referrer
also won’t have a value if the clicked link was marked with the rel="noreferrer"
attribute. Setting rel
to noreferrer
specifically prevents referral information from being passed to the webpage being linked to.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Coding Beauty Tutorial</title>
</head>
<body>
<a href="get-last-page.html">Link</a>
<a href="get-last-page" rel="noreferrer">Link (noreferrer)</a>
</body>
</html>
Navigating to the Previous Page
Perhaps you would like to get the previous page URL so that you can navigate to that page. You can do this easily with the history.back()
method.
get-last-page.js
...
const backButton = document.getElementById('back');
backButton.onclick = () => {
history.back();
};
get-last-page.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Coding Beauty Tutorial</title>
</head>
<body>
You visited this page from: <span id="last-page"></span> <br />
<br />
<button id="back">Back</button>
<script src="get-last-page.js"></script>
</body>
</html>
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.