Read cookies from within a Service Worker?
Asked Answered
C

2

8

I would like to read a cookie within my service worker to use it when setting up my caches, but can't find any way of doing it.

Is there any way of doing that, or will I need to duplicate cookie data into IDB or similar?

Censer answered 17/2, 2016 at 3:50 Comment(0)
U
14

Currently, you can't access them. There's a discussion in the W3C ServiceWorker repo about adding methods to access them in the future.

Uniliteral answered 17/2, 2016 at 10:3 Comment(1)
They have now published a draft for a new spec called CookieStore that covers that use case wicg.github.io/cookie-storeHaubergeon
N
0

Now there is cookieStore property available in some browsers. It is experimental and does not work on every browser though.

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/cookieStore

So you just need to access ServiceWorkerGlobalScope and call get function.

const cookie = await this.cookieStore.get("_ga");

return cookie?.value;

It's not currectly available in firefox, but it seems to be work in progress: https://github.com/mozilla/standards-positions/issues/94#issuecomment-2192528669

Near answered 23/7, 2024 at 13:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.