Thursday, 28 July 2022

Javascript - How to get the previous URL in JavaScript?

 https://stackoverflow.com/questions/3528324/how-to-get-the-previous-url-in-javascript


1) document.referrer (will show the previous page redirected to current page, but it might not always be accurate)


2) 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, 56, etc.


This might not always work especially for single page application since entire window is reloaded when redirected from one single page application to another


# Recommended front end solution 

3)

// Set in local storage of browser

 localStorage.setItem("previous-url", projectUrl)

// Retrieve

 localStorage.getItem("previous-url")

// Remove
   localStorage.removeItem("previous-url")

// Cons for this approach is localStorage has to be manually cleaned through localStorage.removeItem(),
or through user hard reload page. 

No comments:

Post a Comment