0
Page A
Page B
Page C

If the user is coming from page A do something on page C (within the same website) If the user is coming from page B do something else on page C (within the same website)

What would be the best approach to do that in JS? (dont use document.referrer)

Barmar
  • 741,623
  • 53
  • 500
  • 612

4 Answers4

1

In my opinion, there are two decent solutions:

  1. When Page A loads Page C, include a variable in the URL that essentially says "loaded from page A". (Same applies to Page B.)

  2. When Page A is loaded, set either a cookie, localStorage, or sessionStorage variable that says "loaded from page A". (Same applies for Page B.) Then when Page C is loaded, check the variable to see if either Page A or Page B was the most recently opened page. (You may also want to set a timeout/expiration-time on the cookie, localStorage, or sessionStorage.)

Spencer D
  • 3,376
  • 2
  • 27
  • 43
0

What you can do is have a global variable that will hold the location. When you load a page. assign that variable the location

window.location.href 

or

document.URL;

Another option would be using cookies.

myselfmiqdad
  • 2,518
  • 2
  • 18
  • 33
  • A "global variable" in the Javascript sense (i.e. stored in `window`) would be lost when switching from one page to another. – jcaron Dec 09 '15 at 23:04
  • It is not stored in windows, you get the current url from windows. The javascript variable remains constant and therefore accessible from multiple pages on the site. – myselfmiqdad Dec 09 '15 at 23:08
  • Try it. You'll see it isn't. As long as we are talking about a regular Javascript variable, i.e. not cookies, local storage, session storage, etc, of course. – jcaron Dec 09 '15 at 23:12
0

Your description doesnt make a lot of sense (to me), especially because you havent included any framework/stack you're using (which this responsibility would likely fall on).

That said, I would use a variable with session getters and setters. You can parse the query string or URL, set that equal to a session variable, then get that session variable when you're ready to use it.

Here's how to use session getters and setters in javascript

Community
  • 1
  • 1
redress
  • 1,399
  • 4
  • 20
  • 34
  • Let say that I am not using any framework... I am looking for a clean js solution. I want to do sessionStorage with a fallback to cookies for old browsers but wanted to make sure if that is the best solution... – user3195927 Dec 09 '15 at 23:18
0

You can have page A and page B set a cookie that indicates which page they are. Then page C can check the cookie value.

Barmar
  • 741,623
  • 53
  • 500
  • 612