Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if it is user is visiting first time with javascript

Tags:

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>
like image 727
Sahibjot Singh Avatar asked Oct 26 '25 13:10

Sahibjot Singh


2 Answers

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
}
like image 131
Peter B Avatar answered Oct 29 '25 01:10

Peter B


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);
like image 43
Alexander Sanik Avatar answered Oct 29 '25 01:10

Alexander Sanik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!