Sahibjot Singh
Sahibjot Singh

Reputation: 1391

Check if it is user is visiting first time with javascript

I'm trying to build a system where, if user lands on a page for the first time nothing should happen, but if same user visit again then that page should not load and instead he should go to a different URL.

function session() {
    if (document.cookie.indexOf("visited") > 0) {
        window.location.href = "www.google.com";
    } else {
        document.cookie = "visited";
    }
}

Here is the completed html just to test it's workig

<html>
<head>
</head>
<body>
    1st visit
    <script type="text/javascript">
    function session() {
        if (document.cookie.indexOf("visited") > 0) {
            window.location.href = "www.google.com";
        } else {
            document.cookie = "visited";
        }
    }
    </script>
</body>
</html>

Upvotes: 4

Views: 7245

Answers (3)

Tameem AS
Tameem AS

Reputation: 13

You may do this

function userfirstcheck(){
  var usercheck = localStorage.getItem('delete')
  if(usercheck == null){
    alert('hi')
    localStorage.setItem("delete", "userforfirst")
  }
  else if(usercheck != null){
    alert('welcome back')
  }
}
<body onload="userfirstcheck()">

Upvotes: 0

Alexander Sanik
Alexander Sanik

Reputation: 198

I'm recommend to use local storage =)

    var first_visit = false;
    checkFirstVisit();
    function checkFirstVisit(){
        if(localStorage.getItem('was_visited')){
            return;
        }
        first_visit = true;
        localStorage.setItem('was_visited', 1);
    }
    console.log(first_visit);

Upvotes: 3

Peter B
Peter B

Reputation: 24187

Here is a solution based on the Duplicate link that I posted.

I am not posting it as a Code Snippet, because for security reasons Code Snippets can't seem to work with cookies. Instead here is a working JSFiddle.

function setCookie(c_name,value,exdays){var exdate=new Date();exdate.setDate(exdate.getDate() + exdays);var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());document.cookie=c_name + "=" + c_value;}

function getCookie(c_name){var c_value = document.cookie;var c_start = c_value.indexOf(" " + c_name + "=");if (c_start == -1){c_start = c_value.indexOf(c_name + "=");}if (c_start == -1){c_value = null;}else{c_start = c_value.indexOf("=", c_start) + 1;var c_end = c_value.indexOf(";", c_start);if (c_end == -1){c_end = c_value.length;}c_value = unescape(c_value.substring(c_start,c_end));}return c_value;}

checkSession();

function checkSession(){
   var c = getCookie("visited");
   if (c === "yes") {
     alert("Welcome back!");
   } else {
     alert("Welcome new visitor!");
   }
   setCookie("visited", "yes", 365); // expire in 1 year; or use null to never expire
}

Upvotes: 10

Related Questions