mr_simti
mr_simti

Reputation: 19

IOS: javascript cookie not working on ios browsers like safari or chrome

I'm working with js to store my shopping list in cookie.it works fine on windows or Macintosh or android mobiles but not working on iphone mobile browsers(safari and chrome).in food page I add foods to my list and after refreshing the page or redirecting to other pages,cookie is empty.

i've tried two ways to write the cookie and also played with cookie parameters but the problem is still there.

here's my code to set cookie:

function bake_cookie(name, value) {
  var date, 
  date = new Date();
  date.setTime(date.getTime()+(30*24*60*60*1000));
  var cookie = [name, '=', JSON.stringify(value), '; domain=', "", '; 
  path=','/; expires='+date.toUTCString()+"';"].join('');
  document.cookie = cookie;
}

my value is an array of objects like this:

[
  {
   count: 3
   food_id: 2
   kitchen_name: "kitchen 1"
   pic: "url"
   title: "food 1"
   total_price: 21000
   unit_price: 7000
  },
  {
   count: 5
   food_id: 7
   kitchen_name: "kitchen 2"
   pic: "url"
   title: "food 2"
   total_price: 25000
   unit_price: 5000
  },...
]

to update it first i delete the cookie like this:

function delete_cookie(name) {
  document.cookie = [name, '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; 
  domain=', ""].join('');
}

then I call bake_cookie() with new inputs.

Upvotes: 1

Views: 5654

Answers (4)

Henshal B
Henshal B

Reputation: 2002

Try to make cookie secure: false for development environment.
Secure cookies are allowed when the traffic is encrypted using TLS.

Upvotes: 0

jjp228
jjp228

Reputation: 1

In my case the issue was the path not being set correctly. It works fine on desktop but doesn't work on Chrome for iOS.


The following doesn't work:

path=https://example.com/path

Changed to the following fixed the issue:

path=/path

Upvotes: 0

Platoscave
Platoscave

Reputation: 339

I can see this isn't the answer in this case, but just adding incase useful for someone else in the future. I found iOS devices would only set an 'expires' date/time if it was set to UTC (.toUTCString()) without this it would only set the cookie as a session cookie.

Upvotes: 0

Christian Davén
Christian Davén

Reputation: 18237

Let me guess, your cookie contains non-ASCII characters? That works fine in all environments except on iOS. A solution is to URL encode and URL decode.

Another solution is to use js-cookie, which will handle this transparently.

Upvotes: 4

Related Questions