Skip to content

Commit 585c85b

Browse files
authored
Test out fetch-with-keepalive on plausible.io (#5005)
* Test out fetch-with-keepalive on plausible.io Fetch with keepalive is a [widely-supported](https://developer.mozilla.org/en-US/docs/Web/API/Request/keepalive) which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. We're hoping it will improve event capture rates for `pageleave` and `pageview` events when the user closes the tab To use it, we also need to start using `fetch` (with fallback to xhr). For extra safety, we will only deploy this on `plausible.io` initially. This will ensure that if there are issues we will be able to react without affecting any other customers. TODO after this PR: - [ ] Companion docs PR - [ ] Purge bunny cache - [ ] Make fetch the default request method without data-property * Mark some code conditional
1 parent 4f98259 commit 585c85b

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

lib/plausible_web/templates/layout/_tracking.html.heex

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
data-api={PlausibleWeb.Dogfood.api_destination()}
66
data-domain={PlausibleWeb.Dogfood.domain(@conn)}
77
src={PlausibleWeb.Dogfood.script_url()}
8+
data-allow-fetch
89
>
910
</script>
1011
<script>

tracker/src/plausible.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
{{/if}}
1212
var endpoint = scriptEl.getAttribute('data-api') || defaultEndpoint(scriptEl)
1313
var dataDomain = scriptEl.getAttribute('data-domain')
14+
var allowFetch = scriptEl.hasAttribute('data-allow-fetch')
1415

1516
function onIgnoredEvent(eventName, reason, options) {
1617
if (reason) console.warn('Ignoring Event: ' + reason);
@@ -221,6 +222,27 @@
221222
}
222223
{{/if}}
223224

225+
sendRequest(endpoint, payload, options)
226+
}
227+
228+
function sendRequest(endpoint, payload, options) {
229+
{{#if pageleave}}
230+
if (allowFetch && window.fetch) {
231+
fetch(endpoint, {
232+
method: 'POST',
233+
headers: {
234+
'Content-Type': 'text/plain'
235+
},
236+
keepalive: true,
237+
body: JSON.stringify(payload)
238+
}).then(function(response) {
239+
options && options.callback && options.callback({status: response.status})
240+
})
241+
242+
return
243+
}
244+
{{/if}}
245+
224246
var request = new XMLHttpRequest();
225247
request.open('POST', endpoint, true);
226248
request.setRequestHeader('Content-Type', 'text/plain');
@@ -232,6 +254,7 @@
232254
options && options.callback && options.callback({status: request.status})
233255
}
234256
}
257+
235258
}
236259

237260
var queue = (window.plausible && window.plausible.q) || []

0 commit comments

Comments
 (0)