Theopap
Theopap

Reputation: 755

Check if cookie exist in a javascript

I have the following JavaScript on my rails app and I want to run it only when the cookie doesn't exist.

function getGeoLocation() {
    navigator.geolocation.getCurrentPosition(setGeoCookie);
}

function setGeoCookie(position) {
    var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
    document.cookie = "lat_lng=" + escape(cookie_val);
}

I'm using this to call the script on my rails app:

 <%- unless @lat_lng %>
        <script>
            getGeoLocation();
        </script>
  <%- end %>

Update

I updated my application.js file according to @Njdhv answer and the popup still appears. Here is what I did:

function getCookieByName(name) {
var parts = document.cookie.split('; '),
    len = parts.length,
    item, i, ret;
for (i = 0; i < len; ++i) {
    item = parts[i].split('=');
    if (item[0] === name) {
        ret = item[1];
        return ret ? unescape(ret) : '';
    }
    }
 return null;
}

if(getCookieByName('lat_lng') != null){
    console.log('lat_lng')
    function getGeoLocation() {
        navigator.geolocation.getCurrentPosition(setGeoCookie);
    }

    function setGeoCookie(position) {
        var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
       document.cookie = "lat_lng=" + escape(cookie_val);
    }
}else{
//you can put your logic here...
}

Upvotes: 1

Views: 1299

Answers (4)

Theopap
Theopap

Reputation: 755

I found out what was the problem, I had to change this inside my view:

from this:

 <%- unless @lat_lng %>
    <script>
        getGeoLocation();
    </script>
<%- end %>

to this:

<% if cookies[:lat_lng].nil? %>
    <script>
        getGeoLocation();
    </script>
<% end %>

Upvotes: 2

Narendra Jadhav
Narendra Jadhav

Reputation: 10262

You can Read all cookies using document.cookie accessible from curent location.

As per your requirement as you need read and write cookie in your application so you can create your own Singleton for cockie get , set and clear(remove).

The Singleton Pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.

Here below I have create an Singleton name is cookieUtility

var cookieUtility = (function() {
    return {
        /**
         * Creates a cookie with the specified name and value. Additional settings for the cookie may be optionally specified
         * (for example: expiration, access restriction, SSL).
         * @param {String} name The name of the cookie to set.
         * @param {Object} value The value to set for the cookie.
         * @param {Object} [expires] Specify an expiration date the cookie is to persist until. Note that the specified Date
         * object will be converted to Greenwich Mean Time (GMT).
         * @param {String} [path] Setting a path on the cookie restricts access to pages that match that path. Defaults to all
         * pages ('/').
         * @param {String} [domain] Setting a domain restricts access to pages on a given domain (typically used to allow
         * cookie access across subdomains). For example, "sencha.com" will create a cookie that can be accessed from any
         * subdomain of sencha.com, including www.sencha.com, support.sencha.com, etc.
         * @param {Boolean} [secure] Specify true to indicate that the cookie should only be accessible via SSL on a page
         * using the HTTPS protocol. Defaults to false. Note that this will only work if the page calling this code uses the
         * HTTPS protocol, otherwise the cookie will be created with default options.
         */
        set: function(name, value) {
            var argv = arguments,
                argc = arguments.length,
                expires = (argc > 2) ? argv[2] : null,
                path = (argc > 3) ? argv[3] : '/',
                domain = (argc > 4) ? argv[4] : null,
                secure = (argc > 5) ? argv[5] : false;
            document.cookie = name + "=" + escape(value) + ((expires === null) ? "" : ("; expires=" + expires.toUTCString())) + ((path === null) ? "" : ("; path=" + path)) + ((domain === null) ? "" : ("; domain=" + domain)) + ((secure === true) ? "; secure" : "");
        },
        /**
         * Retrieves cookies that are accessible by the current page. If a cookie does not exist, `get()` returns null. The
         * following example retrieves the cookie called "valid" and stores the String value in the variable validStatus.
         *
         *
         * @param {String} name The name of the cookie to get
         * @return {Object} Returns the cookie value for the specified name;
         * null if the cookie name does not exist.
         */
        get: function(name) {
            var parts = document.cookie.split('; '),
                len = parts.length,
                item, i, ret;
            // In modern browsers, a cookie with an empty string will be stored:
            // MyName=
            // In older versions of IE, it will be stored as:
            // MyName
            // So here we iterate over all the parts in an attempt to match the key.
            for (i = 0; i < len; ++i) {
                item = parts[i].split('=');
                if (item[0] === name) {
                    ret = item[1];
                    return ret ? unescape(ret) : '';
                }
            }
            return null;
        },
        /**
         * Removes a cookie with the provided name from the browser
         * if found by setting its expiration date to sometime in the past.
         * @param {String} name The name of the cookie to remove
         * @param {String} [path] The path for the cookie.
         * This must be included if you included a path while setting the cookie.
         */
        clear: function(name, path) {
            if (this.get(name)) {
                path = path || '/';
                document.cookie = name + '=' + '; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=' + path;
            }
        }
    }
})();

How to use it ?

1) for getting cookie

cookieUtility.get('name')//need to pass cookie name

2) for setting cookie

cookieUtility.set('name','value')//need to pass cookie name and value of cookie 

3) for remove cookie

cookieUtility.clear('name') //need to pass cookie name and path(if required)

Upvotes: 0

Nisal Edu
Nisal Edu

Reputation: 7591

When you have more than one cookie saved your searching cookie may not be the first ccokie in the cookie array you have to search for "lat_lng" and " lat_lng" both.

    var lat_lng;

        if (navigator.cookieEnabled) {
          cookieArray = document.cookie.split(";");
          cookieArray.forEach(myFunction);

          console.log(cookieArray)

          function myFunction(item, index) {
            if (item.split("=")[0] == " lat_lng" || item.split("=")[0] == "lat_lng") {
              lat_lng = item.split("=")[1];
              console.log("lat_lng " + lat_lng)
            }
          }
        }

if(lat_lng == null){

  //what you want to happen

}

Upvotes: 0

Jochem
Jochem

Reputation: 16

The documentation of javascript explains this very well.

With document.cookie you can check if an cookie exists. simply combining this with an if statement would look something like this:

if (document.cookie == null) {
// do nothing
}
else {
// run it!
}

Upvotes: -1

Related Questions