0

I am trying to implement a link that will take me back to the page it last came from. So on site A I submit a form and it goes to site B where when a link is clicked it should go to site A.

here are the code for the two pages. site A:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<a href="http://www.example.com/testbackpage2.html">link to page 2</a>
<p>My first paragraph.</p>

</body>
</html>

site B:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<script type="text/javascript">
var ex=document.referrer;
document.write(ex);
</script>
<a href="ex">go back to page one</a>
<p>My first paragraph.</p>

</body>
</html>

</body>
</html>
Emily
  • 1
  • 1
  • 3

4 Answers4

1

To go back one page simply use window.history.go(-1) or window.history.back()

<a href="#" onclick="window.history.go(-1)">go back to page one</a>

More info on this API can be found here: https://developer.mozilla.org/en-US/docs/Web/API/Window/history

Jamiec
  • 133,658
  • 13
  • 134
  • 193
1
top.location = document.referrer;
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
very tall
  • 56
  • 2
  • 2
    Although this code might (or might not) solve the problem, a good answer should also explain **what** the problem is and **how** the code helps. – BDL Jul 01 '19 at 08:29
  • But document.referrer returns empty string "" if user comes to a page by clicking a hyperlink. – Jyoti Duhan Aug 17 '21 at 17:32
0

You can try like this

(How to get previous page url using jquery)

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

Or

you can also try,

<a href="javascript: history.go(-1)">Back</a>

From this link

Hope it helps.

Sunil Dora
  • 1,407
  • 1
  • 13
  • 26
  • may I ask what you mean by "t is not always available though". Are there any cases where this wont work? like specific browsers? mobile version? or something else? otherwise it looks neat. Thanks – Emily Oct 11 '17 at 11:32
  • sorry, it's added by mistake. Really sorry. – Sunil Dora Oct 11 '17 at 11:36
  • The first method will not work if the person arrived at a page through a method other than a link. In your example, let's say the user went to page B via a link from page A, but then used the back button to get back to A, and then the forward button to get back to B. In that case only history.back or history.go(-1) would work. – clayRay Apr 08 '19 at 02:18
0

use simple to go back in Jswindow.location = document.referrer;