Skip to content

Commit b74ef2e

Browse files
🐛 fix stale closure bug in watchCookieFallback (#4259)
1 parent 535ee16 commit b74ef2e

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

packages/rum-core/src/browser/cookieObservable.spec.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,34 @@ describe('cookieObservable', () => {
7878

7979
expect(cookieChange).toBeUndefined()
8080
})
81+
82+
it('should not re-notify observers if the cookie has not changed since last notification when cookieStore is not supported', () => {
83+
Object.defineProperty(window, 'cookieStore', { get: () => undefined, configurable: true })
84+
const observable = createCookieObservable(mockRumConfiguration(), COOKIE_NAME)
85+
86+
const cookieChanges: Array<string | undefined> = []
87+
subscription = observable.subscribe((change) => cookieChanges.push(change))
88+
89+
setCookie(COOKIE_NAME, 'foo', COOKIE_DURATION)
90+
clock.tick(WATCH_COOKIE_INTERVAL_DELAY) // detects 'foo'
91+
clock.tick(WATCH_COOKIE_INTERVAL_DELAY) // no change since last notification
92+
93+
expect(cookieChanges).toEqual(['foo'])
94+
})
95+
96+
it('should notify observers on consecutive cookie changes when cookieStore is not supported', () => {
97+
Object.defineProperty(window, 'cookieStore', { get: () => undefined, configurable: true })
98+
const observable = createCookieObservable(mockRumConfiguration(), COOKIE_NAME)
99+
100+
const cookieChanges: Array<string | undefined> = []
101+
subscription = observable.subscribe((change) => cookieChanges.push(change))
102+
103+
setCookie(COOKIE_NAME, 'foo', COOKIE_DURATION)
104+
clock.tick(WATCH_COOKIE_INTERVAL_DELAY)
105+
106+
setCookie(COOKIE_NAME, 'bar', COOKIE_DURATION)
107+
clock.tick(WATCH_COOKIE_INTERVAL_DELAY)
108+
109+
expect(cookieChanges).toEqual(['foo', 'bar'])
110+
})
81111
})

packages/rum-core/src/browser/cookieObservable.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,11 @@ function listenToCookieStoreChange(configuration: Configuration) {
4949
export const WATCH_COOKIE_INTERVAL_DELAY = ONE_SECOND
5050

5151
function watchCookieFallback(cookieName: string, callback: (event: string | undefined) => void) {
52-
const previousCookieValue = findCommaSeparatedValue(document.cookie, cookieName)
52+
let previousCookieValue = findCommaSeparatedValue(document.cookie, cookieName)
5353
const watchCookieIntervalId = setInterval(() => {
5454
const cookieValue = findCommaSeparatedValue(document.cookie, cookieName)
5555
if (cookieValue !== previousCookieValue) {
56+
previousCookieValue = cookieValue
5657
callback(cookieValue)
5758
}
5859
}, WATCH_COOKIE_INTERVAL_DELAY)

0 commit comments

Comments
 (0)