Geeth
Geeth

Reputation: 5343

How to get previous page URL using jQuery

How to get previous page URL using jQuery?

I am using the following code to get the current page location

$(document).ready(function() {
var pathname = window.location.pathname;
});

Upvotes: 46

Views: 152199

Answers (9)

Marcos Placona
Marcos Placona

Reputation: 21730

Easy as pie.

$(document).ready(function() {
   var referrer =  document.referrer;
});

It is not always available though.

Upvotes: 107

Jignesh Patel
Jignesh Patel

Reputation: 316

Use can use one of below this

history.back();     // equivalent to clicking back button
history.go(-1);     // equivalent to history.back();

I am using as below for back button

<a class="btn btn-info float-right" onclick="history.back();" >Back</a>

Upvotes: 0

Sameera
Sameera

Reputation: 47

    $(document).ready(function() {
               var referrer =  document.referrer;

               if(referrer.equals("Setting.jsp")){                     
                   function goBack() {  
                        window.history.go();                            
                    }
               }  
                   if(referrer.equals("http://localhost:8080/Ads/Terms.jsp")){                     
                        window.history.forward();
                        function noBack() {
                        window.history.forward(); 
                    }
                   }
    }); 

using this you can avoid load previous page load

Upvotes: -1

Praveen Kumar Sharma
Praveen Kumar Sharma

Reputation: 61

simple & sweet

window.location = document.referrer;

Upvotes: 2

Aman Jain
Aman Jain

Reputation: 665

We have document.referrer for this, but it is not on which we can relay. This could be saved, could be not

$(document).ready(function() {
   var referrer =  document.referrer;
});

The better approach is to add a cookie to store the previous-url in the browser.

Upvotes: 3

Grumpy
Grumpy

Reputation: 2243

Do you mean something like history.go(-1);? It will go back to the previous page.

window.history on MDN

Upvotes: 9

mspapant
mspapant

Reputation: 2050

document.referrer is not working always.

You can use:

window.location.origin

Upvotes: -3

Roel B
Roel B

Reputation: 103

If you are using PHP, you can check previous url using php script rather than javascript. Here is the code:

echo $_SERVER['HTTP_REFERER'];

Hope it helps even out of relevance :)

Upvotes: 6

Amarghosh
Amarghosh

Reputation: 59461

var from = document.referrer;
console.log(from);

document.referrer won't be always available.

Upvotes: 5

Related Questions