Skip to content

Commit

Permalink
count.js: use img-based fallback if sendBeacon fails
Browse files Browse the repository at this point in the history
Mostly for CSP errors; in some cases it's not easy to configure that.
For example NeoCities blocks it by default and allows changing it only
on the paid plan (but does allow `img-src *`).

It just adds a few bytes, so not too bad.
  • Loading branch information
arp242 committed Jun 3, 2024
1 parent 4188f6d commit 10d7e6e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
19 changes: 18 additions & 1 deletion public/count.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,24 @@
var url = goatcounter.url(vars)
if (!url)
return warn('not counting because path callback returned null')
navigator.sendBeacon(url)

if (!navigator.sendBeacon(url)) {
// This mostly fails due to being blocked by CSP; try again with an
// image-based fallback.
var img = document.createElement('img')
img.src = url
img.style.position = 'absolute' // Affect layout less.
img.style.bottom = '0px'
img.style.width = '1px'
img.style.height = '1px'
img.loading = 'eager'
img.setAttribute('alt', '')
img.setAttribute('aria-hidden', 'true')

var rm = function() { if (img && img.parentNode) img.parentNode.removeChild(img) }
img.addEventListener('load', rm, false)
document.body.appendChild(img)
}
}

// Get a query parameter.
Expand Down
3 changes: 2 additions & 1 deletion tpl/help/countjs-versions.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ but you may need to update it in the future for new features.

Latest
------
- Only use `navigator.sendBeacon`, removing the `<img>`-based fallback.
- Use `<img>`-based fallback if `navigator.sendBeacon` fails, for example due to
Content-Security-Policy errors.

v4 (8 Dec 2023)
---------------
Expand Down

0 comments on commit 10d7e6e

Please sign in to comment.