Is there any way to check if the client accepts cookies only with javascript code?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With