I need to get the previous url to redirect to the previous page. I have url like www.mysite/users/register/#1
.
I use document.referrer
to get the previous url,but it doesn't return hash part(#1
). How to get the previous url including hash part?
I need to get the previous url to redirect to the previous page. I have url like www.mysite.com/users/register/#1
.
I use document.referrer
to get the previous url,but it doesn't return hash part(#1
). How to get the previous url including hash part?
- 1 And it's just within your own domain, no referrers from cross origins? You could maybe store the previous url in local storage or a cookie ? – adeneo Commented Apr 6, 2016 at 10:12
- 2 Is this just asking about referrals within your own site? Or from a different origin? – T.J. Crowder Commented Apr 6, 2016 at 10:13
- 3 Have you looked at window.history? – MichaelK Commented Apr 6, 2016 at 10:13
- 2 Possible duplicate of How do you get the previous url in Javascript? – ADreNaLiNe-DJ Commented Apr 6, 2016 at 10:15
- 1 @adeneo Eh... read the question: "I need to get the previous url to redirect to the previous page". So... window.history.back(), hm? – MichaelK Commented Apr 6, 2016 at 10:17
5 Answers
Reset to default 11How to get previous url including hash fragment using JavaScript?
As you've noted, the hash fragment part of that means you can't use document.referrer
.
If the previous page was on the same origin: You'd need to have code on that page recording the full URL, for instance in sessionStorage
.
On the previous page, perhaps each time hashChange
is fired:
sessionStorage.setItem("last-url", location);
On the new page, to get the URL:
var lastUrl = sessionStorage.getItem("last-url");
If the previous page was on a different origin: I'm fairly certain you can't.
I need to get the previous url to redirect to the previous page.
Actually, you don't. You can just use history.go(-1)
or history.back()
to do that, which work regardless of the origin of the previous page.
May be you can use onhashchange event. When url is changed,it produces a event with old url and new url. The oldurl has even the hash part
try for previous url,
function backtopage() {
window.history.back();
}
$(window).bind('statechange',function(){
// Prepare Variables
var State = History.getState(),
url = State.url,
states = History.savedStates,
prevUrlIndex = states.length - 2,
prevUrl = states[prevUrlIndex].hash;
});
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","#");
});