grrr-amsterdam / cookie-consent

Cookie consent with accessible dialog, agnostic tag triggers and conditional content, script and embed hooks.
MIT License
64 stars 11 forks source link

Feature proposal: expose functionality to clean up or migrate old cookie IDs #20

Open carlgieringer opened 3 years ago

carlgieringer commented 3 years ago

I noticed during development that when I changed the IDs of cookies, I would get those old cookie IDs back even though I wasn't interested in them.

One way to handle this would be to provide a setting like unrecognizedCookieIdBehavior which could have the values (where "unrecognized cookies" means "cookies having an ID that doesn't exist in the current settings"):

Here's an example of the type of workaround I had to implement since something like this functionality is missing:

// I need to use this implementation detail to make the fix myself
const PREFS_LOCAL_STORAGE_KEY = 'cookie-consent-preferences'

const settings = {
  // The dialog flashes even when consent has already been given. So add it ourselves.
  append: false,
  cookies: [
    {
      id: REQUIRED_FUNCTIONALITY,
      label: 'Required functionality',
      description: 'Persists your response to this dialog.',
      required: true,
    },
    ...
  ],
}

export function fixConsentCookieIds() {
  const validIds = keyBy(settings.cookies, 'id')
  const prefs = fromJson(window.localStorage.getItem(PREFS_LOCAL_STORAGE_KEY))
  const newPrefs = []
  forEach(prefs, (pref) => {
    if (!validIds[pref.id]) {
      logger.debug(`dropping invalid cookie consent pref ${toJson(pref)}`)
      return
    }
    newPrefs.push(pref)
  })
  window.localStorage.setItem(PREFS_LOCAL_STORAGE_KEY, toJson(newPrefs))
}
harmenjanssen commented 3 years ago

That would be really useful, actually! Would you be willing to submit a PR for that?

I would say we can default to making the config leading. The keys specified in the config should reasonally be the preferences that are acceptable by the script and any alien keys in there ought to be ignored unless otherwise specified (maybe in the case of runtime-generated keys for instance).