3

I´m trying to show (ALERT) the URL of the previous page. So...

<script>
var referrer =  document.referrer;
alert(referrer);
</script>

But doesn´t work. The idea is, for example, if user is on the url: www.domain.com/page2.php and return to the previous with the previous button of the browser, show on the previous, for example, www.domain.com/page1.php an alert msg with the content

www.domain.com/page2.php

The CODE show an empty alert when I charge the page (www.domain.com/page1.php) that has it.

But when I go to the page www.domain.com/page2.php (with a button inside a form) and then, I click over the return arrow of the browser, the code did not execute.

Anyone knows why?

Tom
  • 91
  • 9
  • http://stackoverflow.com/questions/3528324/how-do-you-get-the-previous-url-in-javascript This may help! – hemnath mouli Aug 23 '15 at 02:30
  • What does the code looks like for the parts where you move between pages? Is it a link or is it a single page application? – Soren Aug 23 '15 at 02:39

1 Answers1

5

The reason the code doesn't execute when using the back button is because of the use of something called the backward-forward cache. Here's an MDN article on it: https://developer.mozilla.org/en-US/Firefox/Releases/1.5/Using_Firefox_1.5_caching.

Basically, what it means is that the state of the page is frozen and saved when it's navigated away from. And then when the back button is use to get back to that page, the saved copy is shown, making page load instant, but also causing it to come back in the exact state it was in when the page was left. And since your script had already been run on the page, it won't be run again.

To make your alert show every time the page is loaded, even from cache, you should put it in a pageshow event listener, rather than just running when the script tag is loaded.

BurningLights
  • 2,387
  • 1
  • 15
  • 22
  • you resolved my problem. With and myFunction() in the header... Works great! Thanks, thanks and more thanks! – Tom Aug 23 '15 at 06:38
  • You're welcome! Could you please mark it as the answer if it helped you solve your problem? I'd really appreciate it! – BurningLights Aug 24 '15 at 01:57