Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If user came from previous page on site then this, else do this

What would be a viable way to accomplish the following:

A website has two pages; Parent page and Inside page. If user came to the Inside page directly by typing in the address or by following a link from a page other than Parent page, then show "foo". If user came to the Inside page from the parent page, then show "bar".

I would need this done in JS if possible. If not, PHP is a secondary choice.

like image 481
beliy333 Avatar asked Feb 08 '16 05:02

beliy333


4 Answers

You can get the page the user came from with document.referrer.

So you could implement your solution like this:

if (document.referrer === 'yoursite.com/parentpage') {
  // do bar
} else {
  // do foo
}
like image 120
pedrotp Avatar answered Oct 13 '22 00:10

pedrotp


Please try this

This code in second page

jQuery(window).load(function() {
  if (sessionStorage.getItem('dontLoad') == null) {
    //show bar
  }
  else{
    //show foo
  }
});

This code in parent page

jQuery(window).load(function() {
  sessionStorage.setItem('dontLoad','true') 
});
like image 45
Rino Raj Avatar answered Oct 13 '22 00:10

Rino Raj


with php:

There is a simple way is to create a mediator page which redirect to inner page after make a session / cookie.. then if you'll get session / cookie, you show foo & unset session.

if someone directly come from url, no session / cookie found & it show bar..

like image 20
Munjal Mayank Avatar answered Oct 12 '22 23:10

Munjal Mayank


You can use the document.referrer but this is not always set. You could add a parameter to the URL on the parent page and then check for its existance in the child page

Link on the parent page:

<a href='myChildPage.html?fromParent=1'>My Child Page</a>

JS code on your child page:

var fromParent=false;
var Qs = location.search.substring(1);
var pairs = Qs.split("&");
for(var i = 0; i < pairs.length; i++){
    var pos = pairs[i].indexOf('=');
    if(pos!==-1){
        var paramName = pairs[i].substring(0,pos);
        if(paramName==='fromParent'){
            fromParent=true;
            break;
        }
    }
}

if(fromParent){
    alert("From Parent");
}else{
    alert("NOT From Parent");
}

This method isnt 100% foolproof either as users could type in the same URL as your parent page link. For better accuracy check the document.referrer first and if not set use the method i've outlined above

like image 35
Bug Avatar answered Oct 13 '22 01:10

Bug