Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set Cookie with JavaScript in Safari or iOS

I'm working on some cookie consent and terms etc.. So I made a JS function to set a cookie after user clicks "Agree" button:

...html

<button onclick="setCookie('law_cookie', 'agree_all', 90)">


...js

function setCookie(name, value, daysToLive) {
    // Encode value in order to escape semicolons, commas, and whitespace
    let cookie = name + "=" + encodeURIComponent(value);

    if (typeof daysToLive === "number") {
        /* Sets the max-age attribute so that the cookie expires
        after the specified number of days */
        cookie += ";max-age=" + (daysToLive * 24 * 60 * 60) + ';Secure;path=/';

        document.cookie = cookie;
        cookie_set = true

    }
}

Now I tested in chrom and firefox, everything works great! BUT, safari isn't able to set a cookie. I tried to initialise by clicking on the button but after reload safari hasn't set the cookie.

I checked if javascript was enabled (it was) and I also tried to set cookie = encodeURIComponent(cookie); but nothing works.

Someone has an idea what I'm doing wrong?

like image 582
Vic Wild Avatar asked Oct 15 '25 15:10

Vic Wild


2 Answers

Safari version 15.2, unlike Chrome and Firefox, refuses to set Secure cookies on the localhost origin, so you'll need to add a workaround just for Safari.

like image 162
Charles Avatar answered Oct 18 '25 04:10

Charles


it seems that Safari, unlike Chrome/Firefox - does not store JS cookie that is Secure; if the site is an http

this behavior is not specified on cookies RFC, and MDN (;secure: Specifies that the cookie should only be transmitted over a secure protocol.)

so if you run the following in an http served page JS:

document.cookie = "k1=v1;Secure;";

it will behave the following

  • on most browsers - this will store cookie both from http and https
  • on Safari - this will store the cookie only when executed in https page context

That may explain this behvior

like image 32
user3635325 Avatar answered Oct 18 '25 04:10

user3635325



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!