Skip to content

Commit de328b0

Browse files
committed
feat: Use fetch before sendBeacon
Fetch is more reliable and lets us use headers rather than query strings.
1 parent 3680e07 commit de328b0

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

src/index.ts

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
createBrowserEvent
88
} from '@chiffre/analytics-core'
99
import { Config } from './types'
10+
import { version } from './version'
1011

1112
export function readConfig(): Config | null {
1213
try {
@@ -34,14 +35,14 @@ export function sendEvent(event: Event<any, any>, config: Config) {
3435
const json = JSON.stringify(event)
3536
const payload = encryptString(json, config.publicKey)
3637
const tock = performance.now()
37-
const perf = Math.round(tock - tick)
38-
const url = `${config.pushURL}?perf=${perf}`
38+
const perf = Math.round(tock - tick).toFixed()
39+
const urlWithPerf = `${config.pushURL}?perf=${perf}`
3940
if (window.localStorage.getItem('chiffre:debug') === 'true') {
4041
console.dir({
4142
event,
4243
payload,
4344
perf,
44-
url
45+
urlWithPerf
4546
})
4647
}
4748
if (window.localStorage.getItem('chiffre:no-send') === 'true') {
@@ -52,17 +53,32 @@ export function sendEvent(event: Event<any, any>, config: Config) {
5253
return false
5354
}
5455

55-
// Try sendBeacon first, if available
56+
if ('fetch' in window) {
57+
fetch(config.pushURL, {
58+
method: 'POST',
59+
body: payload,
60+
credentials: 'omit',
61+
cache: 'no-store',
62+
headers: {
63+
'Content-Type': 'text/plain',
64+
'X-Chiffre-Perf': perf,
65+
'X-Chiffre-Version': version,
66+
'X-Chiffre-XHR': 'fetch'
67+
}
68+
})
69+
return true
70+
}
71+
5672
if (
5773
typeof navigator.sendBeacon === 'function' &&
58-
navigator.sendBeacon(url, payload)
74+
navigator.sendBeacon(urlWithPerf, payload)
5975
) {
6076
return true
6177
}
6278

6379
// Fallback to img GET
6480
const img = new Image()
65-
img.src = `${url}&payload=${payload}`
81+
img.src = `${urlWithPerf}&payload=${payload}`
6682
return true
6783
}
6884

0 commit comments

Comments
 (0)