Skip to content

Commit adf9fae

Browse files
committed
fix: allow messages module to load in chrome incognito
1 parent b48bcde commit adf9fae

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

src/Messages.ts

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ type MessageFrame = HTMLIFrameElement & {
4040
metadata: RenderOptions;
4141
contentWindow: Window & { messageId: string };
4242
}
43+
type OccurrenceTrackerState = {
44+
session: { [key: string]: number };
45+
triggers: { [key: string]: Array<Timestamp> };
46+
occurrences: { [key: string]: Array<Timestamp> };
47+
}
4348

4449
class OccurrenceTracker {
4550
recordOccurrence(id: MessageId): void {
@@ -78,10 +83,13 @@ class OccurrenceTracker {
7883
load(): void {
7984
const cache = StorageManager.get(Constants.DEFAULT_KEYS.MESSAGE_OCCURRENCES)
8085
if (cache) {
81-
const json = JSON.parse(cache)
82-
this.session = json.session
83-
this.triggers = json.triggers
84-
this.occurrences = json.occurrences
86+
const json = maybeJSON(cache) as OccurrenceTrackerState
87+
88+
if (json) {
89+
this.session = json.session
90+
this.triggers = json.triggers
91+
this.occurrences = json.occurrences
92+
}
8593
}
8694
}
8795

@@ -139,8 +147,8 @@ export default class Messages {
139147
})
140148
events.on('resume', () => {
141149
const key = Constants.DEFAULT_KEYS.MESSAGE_CACHE
142-
const cache = StorageManager.get(key)
143-
this._messageCache = cache ? JSON.parse(cache) : this._messageCache
150+
const cache = maybeJSON(StorageManager.get(key)) as MessageHash
151+
this._messageCache = cache || this._messageCache
144152

145153
this.occurrenceTracker.load()
146154

test/specs/Messages.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1018,6 +1018,19 @@ describe(Messages, () => {
10181018

10191019
expect(showMessage).toHaveBeenCalledTimes(0)
10201020
})
1021+
1022+
it('recovers from impropr JSON serialization', () => {
1023+
const now = Date.now()
1024+
1025+
jest.spyOn(StorageManager, 'get')
1026+
.mockImplementation(() => 'undefined')
1027+
1028+
events.emit('resume')
1029+
1030+
events.emit('track', { eventName: 'Add to cart' })
1031+
1032+
expect(showMessage).toHaveBeenCalledTimes(0)
1033+
})
10211034
})
10221035

10231036
describe('message preview', () => {

0 commit comments

Comments
 (0)