Unverified Commit 1bcc9234 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Bind sendBeacon to navigator (#26601)

Also ensures that even if the navigator.sendBeacon fails the fetch fallback is used.

Fixes #23856. This is likely, as no reproduction was provided it was not possible to verify if it actually fixes the issue.



## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.

## Documentation / Examples

- [ ] Make sure the linting passes
parent 5520dd3f
...@@ -47,13 +47,26 @@ function onReport(metric: Metric): void { ...@@ -47,13 +47,26 @@ function onReport(metric: Metric): void {
type: 'application/x-www-form-urlencoded', type: 'application/x-www-form-urlencoded',
}) })
const vitalsUrl = 'https://vitals.vercel-insights.com/v1/vitals' const vitalsUrl = 'https://vitals.vercel-insights.com/v1/vitals'
;(navigator.sendBeacon && navigator.sendBeacon(vitalsUrl, blob)) || // Navigator has to be bound to ensure it does not error in some browsers
// https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch
const send = navigator.sendBeacon && navigator.sendBeacon.bind(navigator)
function fallbackSend() {
fetch(vitalsUrl, { fetch(vitalsUrl, {
body: blob, body: blob,
method: 'POST', method: 'POST',
credentials: 'omit', credentials: 'omit',
keepalive: true, keepalive: true,
}) // console.error is used here as when the fetch fails it does not affect functioning of the app
}).catch(console.error)
}
try {
// If send is undefined it'll throw as well. This reduces output code size.
send!(vitalsUrl, blob)
} catch (err) {
fallbackSend()
}
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment