How to Use jQuery to Check if Cookies are Enabled


Use jQuery to Check if Cookies are Enabled

In this Article You Find About How to Use jQuery to Check if Cookies are Enabled a cookie (not the kind with chocolate chips) is a small piece of data sent by a website and stored in a user’s computer by their web browser. This is why if you’ve viewed a particular pair of pants on an eCommerce website recently, you might see an ad for those same pants later when browsing Facebook or reading the New York Times — this kind of integration is made possible through the use of cookies.

Check if Cookies are Enabled

As a user and consumer, you can decide whether or not you choose to enable cookies on your own personal web browser. As a web developer, however, it may be important for you to know if a user has cookies enabled on his or her browser, depending on what kind of project you’re working on. If this is the case, then you can actually check if a user has enabled cookies or not using the following straightforward jQuery snippet:

$(document).ready(function() {

var dt = new Date();

dt.setSeconds(dt.getSeconds() + 60);

document.cookie = “cookietest=1; expires=” + dt.toGMTString();

var cookiesEnabled = document.cookie.indexOf(“cookietest=”) != -1;

if(!cookiesEnabled){

//cookies are not enabled

} });

The snippet above is pretty simple. It works by trying to set a cookie. If it works, then you know that cookies are enabled on the browser. If it doesn’t then you’re out of luck.

Here’s how you would use it:

var c = “Cookies enabled:” + navigator.cookieEnabled;

The result of the variable c would be

Cookies enabled: true

If cookies were enabled on the browser,

Cookies enabled: false

Doesn’t get much more simple and straightforward than that!

 

Leave a Reply

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