Introduction

There is at least (which I know) two methods to find out if cookies are enabled or not. You can use client-side script techniques or server-side techniques. Here I will present client-side technique.

To check if browser supports cookies I’ll create some methods for set, get and enabled and use Navigator.cookieEnabled. Now I will do 2 steps:

  • use window.navigator.cookieEnabled which returns a Boolean value that indicating whether cookies are enabled or not (read-only).
  • or try to set test cookie (if Navigator.cookieEnabled is not available) and try to read value of this cookie.

The code

The client-side script code may look:

var mcookie = {};

mcookie.is_enabled = undefined;

mcookie.get = function(name, value, expires, path, secure) {
    var date, expireDate = '';

    path = path || '/';

    if (expires === undefined) {
        expires = 30;
    }
    if (expires) {
        if ( typeof expires == 'number') {
            date = new Date();
            date.setTime(date.getTime() + (expires * 86400000));
            expires = date;
        }
        expireDate = '; expires=' + expires.toUTCString();
    }
    document.cookie = window.encodeURIComponent(name) + '=' + window.encodeURIComponent(value) + expireDate + '; path=' + path + ((secure) ? '; secure' : '');
};

mcookie.get = function(name) {
    var result = new RegExp('(^|; )' + window.encodeURIComponent(name) + '=([^;]*)').exec(document.cookie);
    return result ? window.decodeURIComponent(result[2]) : null;
};

mcookie.enabled = function() {
    if (mcookie.is_enabled === undefined) {
        if ( typeof window.navigator.cookieEnabled === 'boolean') {
            mcookie.is_enabled = window.navigator.cookieEnabled;
        } else {
            mcookie.set('_test', '1');
            mcookie.is_enabled = Boolean(mcookie.get('_test'));
        }
    }
    return mcookie.is_enabled;
};

Note: I didn’t used here extra closure here around mcookie variable. It’s just an example and be careful that mcookie variable here is in global scope (in browsers window represent global scope) and may overwrite other mcookie variable somewhere.

How to use it

Now, call method mcookie.enabled() to get Boolean if browser support cookies or not. There should be false or true. In method mcookie.enabled I check if browser support cookie only once time and store result in property mcookie.is_enabled. Whenever you call next time method mcookie.enabled() then result will be return from local property mcookie.is_enabled.

Example

I like real examples. So, in that case take a look at my example in lab section and test it in your browser.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Comments

You can leave a response, or trackback from your own site.

Before you add comment see for rules.

Leave a Reply

Your email address will not be published. Required fields are marked *

2a8w6k