Junior
How to check if cookies are enabled in the browser?
sobes.tech AI
Answer from AI
You can check for the presence of cookies by attempting to set and read a test cookie.
// Set a test cookie
document.cookie = "testcookie=true";
// Read cookies
const hasCookie = document.cookie.includes("testcookie");
// Delete the test cookie
document.cookie = "testcookie=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
// hasCookie will be true if cookies are successfully set and read
You can also use navigator.cookieEnabled, but this method is less reliable as it may reflect the overall setting status rather than the ability to set a cookie at the moment for the current site.
// Check via navigator.cookieEnabled
const areCookiesEnabled = navigator.cookieEnabled;