diff --git a/files/en-us/web/api/cookiestore/set/index.md b/files/en-us/web/api/cookiestore/set/index.md index 59850b70fb6a945..0ae039d9f7f9d93 100644 --- a/files/en-us/web/api/cookiestore/set/index.md +++ b/files/en-us/web/api/cookiestore/set/index.md @@ -251,6 +251,113 @@ Even if the values are not displayed, they are still set. {{EmbedLiveSample('Setting a cookie with options', 100, 250)}} +### Setting a cookie with options2 + +The following example sets a cookie by passing an `options` object with `name`, `value`, `expires`, and `partitioned`. + +```html hidden + + +
+``` + +```css hidden +#log { + height: 180px; + overflow: scroll; + padding: 0.5rem; + border: 1px solid black; +} +``` + +```js hidden +const reload = document.querySelector("#reset"); + +reload.addEventListener("click", () => { + window.location.reload(true); +}); + +const logElement = document.querySelector("#log"); + +function log(text) { + logElement.innerText = `${logElement.innerText}${text}\n`; + logElement.scrollTop = logElement.scrollHeight; +} + +function clearLog() { + logElement.innerText = ""; +} +``` + +```js hidden +function logCookie(name, cookie) { + if (cookie) { + log(`${name}:`); + for (const [key, value] of Object.entries(cookie)) { + log(` ${key}: ${value}`); + } + } else { + log(`${name}: Cookie not found`); + } +} +``` + +#### JavaScript + +The code first waits for the cookie to be set: as this operation can fail, the operation is performed in a `try...catch` block and any errors are logged. +The example then gets the new cookie, if it exists, and logs its properties (note the logging and other display code is omitted). + +```js +async function cookieTest() { + clearLog(); + + document.cookie = "test1=Hello; SameSite=None; Secure"; + document.cookie = "test2=Hello2;"; + const day = 24 * 60 * 60 * 1000; + const cookieName = "cookie2"; + try { + // Set cookie: passing options + await cookieStore.set({ + name: cookieName, + value: `${cookieName}-value`, + expires: Date.now() + day, + sameSite: "none", + }); + } catch (error) { + log(`Error setting ${cookieName}: ${error}`); + console.log(error); + } + + // Log the new cookie + const cookie = await cookieStore.get(cookieName); + logCookie(cookieName, cookie); + + const cookie2 = await cookieStore.get("test1"); + logCookie("test1", cookie2); + + const cookie3 = await cookieStore.get("test2"); + logCookie("test2", cookie3); +} +``` + +Note that some logging and other code is omitted for brevity. + +```js hidden +const showCookies = document.querySelector("#showCookies"); + +showCookies.addEventListener("click", () => { + cookieTest(); +}); +``` + +#### Result + +Press **Show cookie** to set the cookie and then display it. +Note that some browsers will only display the `name` and `value`, while others will display all the properties of the cookie. +Even if the values are not displayed, they are still set. + +{{EmbedLiveSample('Setting a cookie with options2', 100, 250)}} + ## Specifications {{Specifications}}