Skip to content

Commit

Permalink
feat: test beforeunload compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
Leoglme committed Feb 18, 2024
1 parent 329d8bc commit 780c0e0
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions public/mon-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,24 @@
const data = { domain: `p-${eventName}-${Math.random()}` }
const headers = { type: 'application/json' }
const blob = new Blob([JSON.stringify(data)], headers)
let eventIsSent = false

if (window.fetch) {
if (navigator.sendBeacon && Blob.prototype.isPrototypeOf(blob)) {
console.log('sendBeacon')
const beaconSent = navigator.sendBeacon(apiUrl, blob)

if (!beaconSent) {
console.log('!beaconSent')
try {
createProject()
eventIsSent = true
} catch {
console.warn('sendBeacon failed')
}
}
}

if (!eventIsSent && window.fetch) {
console.log('fetch')
await fetch(apiUrl, {
body: JSON.stringify(data),
Expand All @@ -35,18 +51,12 @@
method: 'POST',
keepalive: true,
})
} else if (navigator.sendBeacon && Blob.prototype.isPrototypeOf(blob)) {
console.log('sendBeacon')
const beaconSent = navigator.sendBeacon(apiUrl, blob)
}

if (!beaconSent) {
console.log('!beaconSent')
createProject()
}
} else {
if (!eventIsSent) {
console.log('else')
// Si ni fetch ni sendBeacon ne sont disponibles, utilisez XMLHttpRequest
createProject()
// Si ni fetch ni sendBeacon ne sont disponibles, utilisez XMLHttpRequest
createProject()
}
}

Expand Down

0 comments on commit 780c0e0

Please sign in to comment.