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 ee3c832 commit 4a299fe
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion public/mon-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
const apiUrl = 'https://analytics.dibodev.com/projects'

function createProject(callback = null) {
const data = { domain: `onleave${Math.random()}` }
console.log('createProject')
const data = { domain: `createProject${Math.random()}` }

const xhr = new XMLHttpRequest()
xhr.open('POST', apiUrl, true)
Expand All @@ -19,23 +20,28 @@
}

async function onLeave(eventName) {
console.log('onLeave')
const data = { domain: `p-${eventName}-${Math.random()}` }
const headers = { type: 'application/json' }
const blob = new Blob([JSON.stringify(data)], headers)

if (window.fetch) {
console.log('fetch')
await fetch(apiUrl + '/leave', {
body: JSON.stringify(data),
method: 'POST',
keepalive: true,
})
} else if (navigator.sendBeacon && Blob.prototype.isPrototypeOf(blob)) {
console.log('sendBeacon')
const beaconSent = navigator.sendBeacon(apiUrl + '/leave', blob)

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

0 comments on commit 4a299fe

Please sign in to comment.