Using java script,how to check if a user accepts cookies for a domain. Does YUI has any such component to check ?
Asked
Active
Viewed 582 times
1
-
possible duplicate of [Check if the client accepts cookie in javascript?](http://stackoverflow.com/questions/703761/check-if-the-client-accepts-cookie-in-javascript) – Oleg V. Volkov Aug 07 '12 at 12:02
1 Answers
0
Library:
<script type="text/javascript">
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
function areCookiesEnabled() {
var r = false;
createCookie("testing", "Hello", 1);
if (readCookie("testing") != null) {
r = true;
eraseCookie("testing");
}
return r;
}
</script>
Code to run:
<script type="text/javascript">
alert(areCookiesEnabled());
</script>
Remember:
This only works if Javascript are allowed to run!
Credit:
This is the re-post from here. Original author is balexandre.

Community
- 1
- 1

Andrejs Cainikovs
- 27,428
- 2
- 75
- 95
-
Not bad, but I'd set the cookie to be a session cookie rather than let it expire in one day. E.g. if I deactivate my cookies after visiting the site and than revisit it it won't work. :P – Termi Oct 17 '11 at 08:21
-
Yes, sounds reasonable. But this is just for a reference. You can change it to whatever you think is suitable for you. – Andrejs Cainikovs Oct 17 '11 at 08:23