javascriptangulartypescriptaddeventlistenercookiestore

how to use CookieStore in Angular in order to listen to cookie change events


I have an angular component where I would like to perform actions when a specific cookie is changed. I read that I can do it via CookieStore Api (https://developer.mozilla.org/en-US/docs/Web/API/CookieStore/change_event) But when I try to use it in my angular component, the code does not compile:

    ngOnInit() {
   
        if ('cookieStore' in window) {
            // Listen for changes to cookies
            window.cookieStore.addEventListener('change', event => {
                event.changed.forEach(change => {
                    console.log(`Cookie changed: ${change.name} = ${change.value}`);
                }); 
            });
        } else {
            console.log('Cookie Store API is not supported in this browser.');
        }
    }

Error is

TS2339: Property cookieStore does not exist on type Window & typeof globalThis

I am using angular version: 15.2.10. Is there any way I can use the CookieStore Api in my angular code? Either service or component?


Solution

  • It's not enough to define Window.cookieStore, you also need to define the CookieStore type and the event listener overload

    type CookieChangeType = {
      name: string,
      value: string,
      expires: Date,
      domain: string,
    }
    
    interface CookieChangeEvent extends Event {
      changed: CookieChangeType[]
    }
    
    type CookieStore = {
      addEventListener: Window["addEventListener"]
    }
    
    declare global { 
      interface Window { 
        cookieStore: CookieStore; 
        addEventListener(type: String, listener: (this: Window, ev: CookieChangeEvent) => any, useCapture?: boolean): void;
      } 
    }
    

    Now your ngOnInit will use the new types, and not throw any type errors

    ngOnInit() {
      window.cookieStore.addEventListener('change', (event: CookieChangeEvent) => {
        event.changed.forEach((change: CookieChangeType) => {
            console.log(`Cookie changed: ${change.name} = ${change.value}`);
        })
      })
    }