diff --git a/playground/nuxt.config.ts b/playground/nuxt.config.ts index 566d6eab..8d7d845e 100644 --- a/playground/nuxt.config.ts +++ b/playground/nuxt.config.ts @@ -6,6 +6,12 @@ export default defineNuxtConfig({ ], colorMode: { // storage: 'cookie', + // cookieAttrs: { + // path: '/', + // domain: 'localhost', + // secure: true, + // samesite: 'None', + // }, }, compatibilityDate: '2024-09-11', }) diff --git a/src/module.ts b/src/module.ts index 6e1a4a44..8708abe4 100644 --- a/src/module.ts +++ b/src/module.ts @@ -18,6 +18,7 @@ const DEFAULTS: ModuleOptions = { dataValue: '', storageKey: 'nuxt-color-mode', storage: 'localStorage', + cookieAttrs: {}, disableTransition: false, } @@ -178,6 +179,10 @@ export interface ModuleOptions { * @default `localStorage` */ storage?: ColorModeStorage + /** + * Storage cookie's attributes + */ + cookieAttrs?: object /** * The script that will be injected into the head of the page */ diff --git a/src/runtime/plugin.client.ts b/src/runtime/plugin.client.ts index ba09ef08..50460916 100644 --- a/src/runtime/plugin.client.ts +++ b/src/runtime/plugin.client.ts @@ -2,7 +2,7 @@ import { computed, reactive, watch } from 'vue' import type { ColorModeInstance } from './types' import { defineNuxtPlugin, isVue2, isVue3, useRouter, useHead, useState } from '#imports' -import { globalName, storageKey, dataValue, disableTransition, storage } from '#color-mode-options' +import { globalName, storageKey, dataValue, disableTransition, storage, cookieAttrs } from '#color-mode-options' // Initialise to empty object to avoid hard error when hydrating app in test mode const helper = (window[globalName] || {}) as unknown as { @@ -79,7 +79,17 @@ export default defineNuxtPlugin((nuxtApp) => { function setPreferenceToStorage(storageType: typeof storage, preference: string) { switch (storageType) { case 'cookie': - window.document.cookie = storageKey + '=' + preference + + if (Object.keys(cookieAttrs).length) { + let cookieString = storageKey + '=' + preference + for (const key in cookieAttrs) { + cookieString += `; ${key}=${cookieAttrs[key]}` + } + window.document.cookie = cookieString + } + else { + window.document.cookie = storageKey + '=' + preference + } break case 'sessionStorage': window.sessionStorage?.setItem(storageKey, preference)