DevWizard
DevWizard

Reputation: 695

javascript cookie doesn't set expire date

I'm using a cookie in JavaScript to remember the last position on a map, but I just realise that the cookie miss the expire date even if I added.

Here you can test the code

https://www.traffwebdemo.co.uk/parking/basic.html

Here my code, for some reason the only one that accept the expire date (and is actually present if I inspect the cookie) is Opera, the other browsers seems to miss the expire date or they say expire on session (FF).

const setUserPrefs = (mapView) => {
  let cookieStr
  const curZ = mapView.getView().getResolution()
  const mapCen = mapView.getView().getCenter()
  const expdate = new Date()

  // set expire date to one week
  expdate.setTime(expdate.getTime() + (7 * 24 * 60 * 60 * 1000))

  cookieStr = `#${mapCen[0]}#${mapCen[1]}#${curZ}`

  document.cookie = `traffweb${window.location.href}= ${escape(cookieStr)}, expires=${expdate.toUTCString()} path=/`
}

How can I make work this code?

if I use decodeURIComponent(document.cookie); yes I have the cookie exp date but not if I go to application in the dev tools and I don't need to check if is set or not to be honest, simply close the browser and reopen it in the same link and the map is not on the same position, it work just on session.

Upvotes: 0

Views: 455

Answers (1)

mplungjan
mplungjan

Reputation: 177684

Just NEVER set your own cookies. Use a library that is tested such as https://github.com/js-cookie/js-cookie - your content breaks the cookie

<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

using

let cookieName = location.href.split("/").slice(-2); 
cookieName.pop(); // get rid of file name
const curZ = mapView.getView().getResolution()
const mapCen = mapView.getView().getCenter()
let cookieStr = `#${mapCen[0]}#${mapCen[1]}#${curZ}`
Cookies.set("traffweb"+cookieName, cookieStr , { expires: 7, path: '/' });

Upvotes: 1

Related Questions