How to get previous url including hash fragment using javascript?

I need the previous URL to be redirected to the previous page. I have a url like www.mysite.com/users/register/#1 .

I use document.referrer to get the previous url but it does not return the hash part ( #1 ). How to get previous url including hash part?

+7
javascript
source share
5 answers

How to get previous url including hash fragment using javascript?

As you noted, part of the hash fragment means that you cannot use document.referrer .

If the previous page was on the same origin : you will need to have the code on this page where the full URL will be written, for example, in sessionStorage .

On the previous page, perhaps each time hashChange started:

 sessionStorage.setItem("last-url", location); 

On a new page, to get the url:

 var lastUrl = sessionStorage.getItem("last-url"); 

If the previous page was in a different source : I'm sure you cannot.

I need the previous URL to be redirected to the previous page.

Actually, you are not doing this. You can simply use history.go(-1) or history.back() , which work regardless of the origin of the previous page.

+6
source share

try using the previous url

  function backtopage() { window.history.back(); } 
+1
source share

Perhaps you can use the onhashchange event. When url is changed, it creates an event with old url and new url. Oldurl has even a hash part

+1
source share
 $(window).bind('statechange',function(){ // Prepare Variables var State = History.getState(), url = State.url, states = History.savedStates, prevUrlIndex = states.length - 2, prevUrl = states[prevUrlIndex].hash; }); 
0
source share

 Try this one:: In previous page url: www.mysite.com/users/register/#1 In Current Page: $(document).ready(function() { var referrerUrl = document.referrer.replace("#","e"); var correctUrl=referrerUrl.replace("e","#"); }); 
-one
source share

All Articles