Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

javascript - Using persist cookies with react on mobile devices

I had trouble loading the token cookie in my PWA (Progressive Web App) when storing and loading it from the application cookies. On the desktop web (Browser) the cookie appears as normal and could be loaded/restored normally. On mobile devices even if the PWA was installed as a web app on the Android device, the cookie disappears after a while (normally within half ane hour). Which is exactly the default of cookie expire.

The default time for a Cookie to expire is 30 minutes.

Question: how to solve this?

Question 2: why does it work longer on desktop browsers?

question from:https://stackoverflow.com/questions/66056337/using-persist-cookies-with-react-on-mobile-devices

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The answer to question 1 is to explicit set the expire time of the cookie. Only then the mobile device sets the cookies from sesion cookie to a long life one and the mobile browser recognize it again and can load and restore the cookie.

Plain JavaScript:

var timeInSeconds = 60; 
document.cookie = 'token=XX;expires='+timeInSeconds+';path=/';

With js-cookies:

var timeInDays = 1; 
Cookies.set("token", "XX", {
    expires: timeInDays,
    path: "/",
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...