Skip to content

Commit

Permalink
πŸ› fallback to xhr when sendBeacon throws (#796)
Browse files Browse the repository at this point in the history
* πŸ› fallback to xhr when sendBeacon throws

* πŸ› avoid a loop of reporting errors if beacon systematically throws
  • Loading branch information
bcaudan authored Apr 19, 2021
1 parent f92eeb6 commit d82d91a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
11 changes: 11 additions & 0 deletions packages/core/src/transport/transport.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,17 @@ describe('request', () => {
expect(navigator.sendBeacon).toHaveBeenCalled()
expect(server.requests.length).toEqual(1)
})

it('should fallback to xhr when sendBeacon throws', () => {
spyOn(navigator, 'sendBeacon').and.callFake(() => {
throw new TypeError()
})

request.send('{"foo":"bar1"}\n{"foo":"bar2"}', 10)

expect(navigator.sendBeacon).toHaveBeenCalled()
expect(server.requests.length).toEqual(1)
})
})

describe('batch', () => {
Expand Down
20 changes: 16 additions & 4 deletions packages/core/src/transport/transport.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Context } from '../tools/context'
import { getTimeStamp, relativeNow } from '../tools/timeUtils'
import { addEventListener, DOM_EVENT, jsonStringify, noop, objectValues } from '../tools/utils'
import { monitor } from '../domain/internalMonitoring'
import { monitor, addErrorToMonitoringBatch } from '../domain/internalMonitoring'

// https://en.wikipedia.org/wiki/UTF-8
const HAS_MULTI_BYTES_CHARACTERS = /[^\u0000-\u007F]/
Expand All @@ -20,9 +20,13 @@ export class HttpRequest {
send(data: string | FormData, size: number) {
const url = this.withBatchTime ? addBatchTime(this.endpointUrl) : this.endpointUrl
if (navigator.sendBeacon && size < this.bytesLimit) {
const isQueued = navigator.sendBeacon(url, data)
if (isQueued) {
return
try {
const isQueued = navigator.sendBeacon(url, data)
if (isQueued) {
return
}
} catch (e) {
reportBeaconError(e)
}
}
const request = new XMLHttpRequest()
Expand All @@ -37,6 +41,14 @@ function addBatchTime(url: string) {
)}`
}

let hasReportedBeaconError = false
function reportBeaconError(e: unknown) {
if (!hasReportedBeaconError) {
hasReportedBeaconError = true
addErrorToMonitoringBatch(e)
}
}

export class Batch {
private pushOnlyBuffer: string[] = []
private upsertBuffer: { [key: string]: string } = {}
Expand Down

0 comments on commit d82d91a

Please sign in to comment.