繁体   English   中英

javascript cookie未设置到期日期

[英]javascript cookie doesn't set expire date

我在JavaScript中使用Cookie来记住地图上的最后位置,但我只是意识到即使我添加了Cookie,它也会错过过期日期。

在这里您可以测试代码

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

在这里,出于某种原因,我的代码是唯一一个接受过期日期(并且在我检查Cookie时实际上存在)的代码是Opera,其他浏览器似乎错过了过期日期,或者它们说在会话(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=/`
}

如何使该代码生效?

如果我使用解码URIComponent(document.cookie); 是的,我有cookie的到期日,但是如果我进入开发工具中的应用程序,就没有了,并且我不需要检查是否已设置,或者说实话,只需关闭浏览器并在同一链接中重新打开它,地图就可以不在同一位置,它仅在会话中起作用。

永远不要设置自己的cookie。 使用经过测试的库,例如https://github.com/js-cookie/js-cookie-您的内容会破坏cookie

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

运用

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: '/' });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM