JavaScript allows you to create dynamic websites and applications easily. Sometimes you may need to get previous page in JavaScript. It is useful if you want to navigate back to the previous URL. In this article, we will learn how to get previous URL in JavaScript.
How to Get Previous URL in JavaScript
In most cases, when a user visits a web page, the past page’s URL is stored in document.referrer object.
document.referrer
In most cases, if the user reached the current page by clicking a link, this contains the URL of previous page. It does not work if the user has directly typed the current page’s URL in address bar of web browser or reached the page via form submission.
You can also use history.back() to go back to previous page.
history.back(); //Go to the previous page history.forward(); //Go to the next page in the stack history.go(index); //Where index could be 1, -1, 6, etc. OR window.history.back(); //Go to the previous page window.history.forward(); //Go to the next page in the stack window.history.go(index); //Where index could be 1, -1, 6, etc.
Alternatively, you can also use other techniques such as storing previous page’s value in cookie, URL parameter or server side.
In this short article, we have learnt how to get previous URL in JavaScript. This is useful for navigation on websites and web applications.
Also read:
How to Get Client Timezone & Offset in JavaScript
How to Check if JS Object Has Property
How to Auto Increment With Prefix as Primary Key in MySQL
How to Set Initial Value & Auto Increment in MySQL
How to Create DMARC Record for your Domain
Related posts:
How to Select Element By Text in JavaScript
How to Get Value of Text Input Field With JavaScript
How to Get Element's Outer HTML using jQuery
How to Convert UTC Date Time to Local Date Time in JS
How to Get Last Item in JS Array
How to Validate Decimal Number in JavaScript
How to Get Array Intersection in JavaScript
How to Automatically Scroll to Bottom of Page in JS

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.