Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the client accepts cookie in javascript?

Is there any way to check if the client accepts cookies only with javascript code?

like image 994
Paulo Avatar asked Apr 01 '09 01:04

Paulo


People also ask

How do you check if cookies are enabled JavaScript?

To check whether a setting a cookie is enabled in the browser, you can use the cookieEnabled property in the window. navigator global object in JavaScript. The property will return a Boolean true if cookie enabled and return false if not enabled.

Can you check if HttpOnly cookie exists in JavaScript?

An HttpOnly cookie cannot be accessed by client-side APIs, such as JavaScript. This restriction eliminates the threat of cookie theft via cross-site scripting (XSS). If the browser allowed you to access it then it would be a defect in the browser.

How do I know if a cookie is secure?

Whenever you need to check whether the cookie exists or not, you can send a request to the server that requires authentication & check the response. If its something like 401 Unauthorized or 403 Forbidden , then the cookie probably doesn't exist & you can prompt the user for login.


1 Answers

This should do the trick:

function areCookiesEnabled() {
  document.cookie = "__verify=1";
  var supportsCookies = document.cookie.length >= 1 && 
                        document.cookie.indexOf("__verify=1") !== -1;
  var thePast = new Date(1976, 8, 16);
  document.cookie = "__verify=1;expires=" + thePast.toUTCString();
  return supportsCookies;
}

This sets a cookie with session-based expiration, checks for it's existence, and then sets it again in the past, removing it.

like image 168
Ben Lowery Avatar answered Oct 13 '22 00:10

Ben Lowery