Is it possible to read cookie expiration date using JavaScript?
If yes, how? If not, is there a source I can look at?
There is a work-around to OP's question if you also control the setting of the cookies. I do it like this:
function setCookie(name, value, expiryInDays) {
const d = new Date();
d.setTime(d.getTime() + expiryInDays * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${value}_${d.toUTCString()};expires=${d.toUTCString()}`;
}
function showCookies() {
if (document.cookie.length !== 0) {
const allCookies = document.cookie.split(/;\s*/);
const wrapper = document.getElementById('allCookies');
wrapper.innerHTML = allCookies.reduce((html, cookie, index) => {
const cookieParts = cookie.split('=');
const cookieValueParts = cookieParts[1].split('_');
const cookieHtml = [
`${index + 1}`,
`Cookie name: ${cookieParts[0]}`,
`Cookie value: ${cookieValueParts[0]}`,
`Expires: ${cookieValueParts[1] || 'unknown'}`
].join('
');
return html + `${cookieHtml}
`;
}, '');
}
}