How 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.