Facebook Instant Game JS Cookie Chrome Error

108 Views Asked by At

we have a game made on JavaScript and HTML. All works fine on Safari, Firefox, and on mobile App. The issue is that on Chrome, on the game page Cookies are NOT set.

We usually do this:

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

The function works fine on all the browsers except for Chrome. We even try with a library called js-cookie but it simply doesn't set the values.

Are we missing something?

2

There are 2 best solutions below

0
Ulises On BEST ANSWER

So the problem was the domain. Facebook use:

.facebook.com

But the app on Instant Games has another domain like:

apps-*.apps.fbsbx.com

The cookie is not set because this:

https://blog.heroku.com/chrome-changes-samesite-cookie

I just chane the cookie to add:

{ sameSite: "None", secure: true, expires: 7 }

And that works fine.

3
Mr. Polywhirl On

How are you calling your function? The following function can safely create a cookie in Chrome.

const DAY_IN_MILLIS = 24 * 60 * 60 * 1000;

const createCookie = (name, value = '', days = 0) => {
  const cookie = { [name]: value };
  if (days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * DAY_IN_MILLIS));
    cookie.expires = date.toUTCString();
  }
  return Object.entries({ ...cookie, path: '/' })
    .map(pair => pair.join('=')).join('; ');
};

const setCookie = (name, value, days) => {
  document.cookie = createCookie(name, value, days);
};

console.log(createCookie('username', 'John Doe'));
console.log(createCookie('username', 'John Doe', 1));