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?
We can get the previous page URL in JavaScript with the document. referrer property. For example: const previousPageUrl = document.
The hash of a url can be found by creating a new URL Javascript object from the URL string, and then using its hash property to get the value of the hash fragment. Note that this will include the # character also. If the url does not contains a hash, then an empty string "" will be returned.
In a URL, a hash mark, number sign, or pound sign ( # ) points a browser to a specific spot in a page or website. It is used to separate the URI of an object from a fragment identifier. When you use a URL with a # , it doesn't always go to the correct part of the page or website.
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.
try for previous url,
function backtopage() {
window.history.back();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With