Cookie Watchdog is a lightweight JavaScript library for monitoring cookie availability and detecting changes in real-time. With support for the modern cookieStore
API, this library makes it easy to track cookies and respond to changes, creations, and deletions.
- Monitor specific cookies for changes.
- Detect cookie creation, updates, and deletions.
- Notify with detailed information on cookie changes.
- Clean and extensible API for adding and removing watchers.
npm install cookie-watchdog
Include the library directly in your HTML:
<script src="/cookie-watchdog.js"></script>
import CookieWatchdog from 'cookie-watchdog';
Or, if you're using the CDN version:
const CookieWatchdog = window.CookieWatchdog;
Monitor a specific cookie for changes:
CookieWatchdog.watch('session_id', (change) => {
console.log('Cookie change detected:', change);
});
When the session_id
cookie changes, you might see:
{
name: "session_id",
value: "new_value",
type: "updated" // Possible types: "created", "updated", "deleted", "existing" or "missing"
}
Stop monitoring a specific cookie: Listener will be removed itself when there are not more watched cookies
CookieWatchdog.unwatch('session_id');
cookieName
: Name of the cookie to monitor.callback
: Function to invoke when the cookie changes.options
(optional): An object to configure the watch behavior.untilReady
: If set totrue
, stops listening after the first event that matches the criteria (default:false
).
CookieWatchdog.watch('user_token', (change) => {
console.log(`Token changed:`, change);
}, {
untilReady: true // Stop listening after the first change
});
cookieName
: Name of the cookie to stop monitoring.
CookieWatchdog.unwatch('user_token');
Cookie Watchdog relies on the cookieStore
API, which is supported in modern browsers. If the cookieStore
API is not available, the library will log an error and fail gracefully.
TO-DO cookieStore polyfill based on a pulling for proper support on Safari and Firefox
We welcome contributions to improve Cookie Watchdog! Feel free to open issues, submit pull requests, or suggest improvements.
If you enjoy this project and would like to support me, consider buying me a coffee or becoming a sponsor:
This project is licensed under the MIT License - see the LICENSE file for details.