Skip to content

Commit

Permalink
Add storage test for setting a cookie via the cookieStore API in a se…
Browse files Browse the repository at this point in the history
…rviceworker (#166)

* Add storage test for setting a cookie via the cookieStore API in a serviceworker

* Fix cookie names
  • Loading branch information
sammacbeth authored Oct 12, 2023
1 parent 582b1a6 commit 697ea28
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
20 changes: 19 additions & 1 deletion privacy-protections/storage-blocking/main.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* globals commonTests,THIRD_PARTY_ORIGIN,THIRD_PARTY_TRACKER_ORIGIN,THIRD_PARTY_AD_ORIGIN */
/* globals commonTests,THIRD_PARTY_ORIGIN,THIRD_PARTY_TRACKER_ORIGIN,THIRD_PARTY_AD_ORIGIN,cookieStore */

const storeButton = document.querySelector('#store');
const retriveButton = document.querySelector('#retrive');
Expand Down Expand Up @@ -146,6 +146,24 @@ const tests = [
throw new Error(`Invalid response (${r.status})`);
});
}
},
{
id: 'service worker cookieStore',
store: async (data) => {
await navigator.serviceWorker.register(`./service-worker.js?data=${data}`, { scope: './' });
const resp = await fetch(`./service-worker-set-cookie?name=swcookiestoredata&data=${data}`);
return await resp.text();
},
retrive: async () => {
return (await cookieStore.get('swcookiestoredata')).value;
},
extra: () => {
if (window.cookieStore) {
return cookieStore.get('swcookiestoredata').then(cookie => {
return 'expires in ' + ((cookie.expires - Date.now()) / (1000 * 60 * 60 * 24)).toFixed(2) + ' days';
});
}
}
}
];

Expand Down
12 changes: 12 additions & 0 deletions privacy-protections/storage-blocking/service-worker.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-env serviceworker */
/* global cookieStore */

self.addEventListener('install', (evt) => {
self.skipWaiting();
Expand All @@ -12,4 +13,15 @@ self.addEventListener('fetch', (event) => {
if (event.request.url.includes('/service-worker-data')) {
event.respondWith(new Response(location.search.replace('?data=', '')));
}
if (event.request.url.includes('/service-worker-set-cookie')) {
const url = new URL(event.request.url);
if (globalThis.cookieStore) {
cookieStore.set({
name: url.searchParams.get('name'),
value: url.searchParams.get('data'),
expires: new Date('Wed, 21 Aug 2030 20:00:00 UTC').getTime()
});
}
event.respondWith(new Response('OK'));
}
});

0 comments on commit 697ea28

Please sign in to comment.