Cookie “CookieName” has been rejected because there is already an HTTP-Only cookie but script tried to store a new one

Viewed 1829
 var CookieName = "TestCookie";
  document.cookie = "CookieName=Cheecker; path =/; httponly=false;samesite=None;secure=true;"
     alert(document.cookie);
  if (document.cookie.indexOf(CookieName) == -1) {
    console.log("Cookies are required to use shopping carts.");
  }

  if (document.cookie.indexOf(CookieName) != -1) {
    console.log(
      "Thank you for enabling Third-Party cookies we only using it for our shopping carts"
    );
  }

I want to check if Third-party cookies are enabled in the user browser

1 Answers

You've got a few questions wrapped up here. I'll answer the one you implied with your title: why are you getting the 'Cookie "CookieName" has been rejected...' error?

There are two reasons, both of which can be confirmed on Mozilla's "Using HTTP Cookies" page, in the 'Creating Cookies' section:

First:
HttpOnly is a flag, not a variable. You have httponly=false; in your cookie setting call. It should just be HttpOnly;, and incidentally the same applies for Secure;. Example:

document.cookie = "CookieName=Cheecker; path =/; HttpOnly; samesite=None; Secure;"

Second:
HttpOnly is a setting that restricts cookies to HTP calls only. They can't be accessed by JavaScript... and so they can't be set by JavaScript, either. From Mozilla's page:

Cookies created via JavaScript cannot include the HttpOnly flag.

So. I can't speak to how to figure out whether third-party cookies are set in the user's browser, but you'll resolve your error by removing the HttpOnly flag from your cookie creation call.

Related