Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous url including hash fragment using JavaScript?

Tags:

javascript

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?

like image 446
athira sobhandas Avatar asked Apr 06 '16 10:04

athira sobhandas


People also ask

Can I get previous URL in JavaScript?

We can get the previous page URL in JavaScript with the document. referrer property. For example: const previousPageUrl = document.

How do I find the URL of a hash?

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.

What is a hash in a URL?

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.


3 Answers

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.

like image 91
T.J. Crowder Avatar answered Oct 05 '22 06:10

T.J. Crowder


try for previous url,

    function backtopage() {

    window.history.back();
}
like image 37
Prabhat Sinha Avatar answered Oct 05 '22 06:10

Prabhat Sinha


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

like image 25
sridhar.. Avatar answered Oct 05 '22 07:10

sridhar..