Search code examples
javascriptjquerycookiesjquery-cookie

JQuery Cookie set cookie for specific url issue on IE & Edge


I'm using the JQuery cookie plugin & I'm trying to set a cookie if a user presses a button. It's also very important, that the cookie is only valid for the current page and therefore not for the whole document.

This is what I tried so far:

if ($.cookie('pressed')) { 
    alert("Button is already pressed.")
} else {
    $.cookie('pressed', 'somevalue', { expires: 1, path: window.location.pathname });
    executeSomeFunction();
}  

The code above seems to work fine for Chrome but fails on edge and IE11. In fact, it doesn't even save the cookie in the mentioned browsers.

I'm using the jquery cookie plugin (link here: https://plugins.jquery.com/cookie/)


Solution

  • Nevermind. I found the answer. Apparently there is a bug in IE (and Edge)

    Note regarding Internet Explorer:

    Due to an obscure bug in the underlying WinINET InternetGetCookie implementation, IE’s document.cookie will not return a cookie if it was set with a path attribute containing a filename.

    (From Internet Explorer Cookie Internals (FAQ))

    This means one cannot set a path using path: window.location.pathname in case such pathname contains a filename like so: /check.html (or at least, such cookie cannot be read correctly).

    I fixed it by simply naming the cookie according to the current page url. That way there is a unique cookie name for each page.

    I did it like this:

    if (Cookies.get(window.location.pathname)) { 
        alert("Sie haben dieses Rezept bereits bewertet. Wenn Sie erneut bewerten wollen, können Sie dies nach 24 Stunden tun.")
    } else {
        Cookies.set(window.location.pathname, 'value', { expires: 1, path: '' });
        executeRating(star, voteCount, voteAverage, nodeId);
    }