@@ -159,6 +159,26 @@ export class Dispatch {
159159 return this . dispatchBeacon ( ) . catch ( ( ) => { } ) ;
160160 } ;
161161
162+ private flushSync : EventListener = ( ) => {
163+ if ( document . visibilityState === 'hidden' ) {
164+ if ( this . doRequest ( ) ) {
165+ let flush = this . rum . sendBeacon ;
166+ let backup = this . rum . sendFetch ;
167+
168+ if ( ! this . config . useBeacon ) {
169+ [ flush , backup ] = [ backup , flush ] ;
170+ }
171+
172+ const req = this . createRequest ( ) ;
173+ flush ( req )
174+ . catch ( ( ) => backup ( req ) )
175+ . catch ( ( ) => {
176+ // fail silent
177+ } ) ;
178+ }
179+ }
180+ } ;
181+
162182 /**
163183 * Automatically dispatch cached events.
164184 */
@@ -177,19 +197,12 @@ export class Dispatch {
177197 //
178198 // A third option is to send both, however this would increase
179199 // bandwitch and require deduping server side.
180- this . config . useBeacon
181- ? this . dispatchBeaconFailSilent
182- : this . dispatchFetchFailSilent
200+ this . flushSync
183201 ) ;
184202 // Using 'pagehide' is redundant most of the time (visibilitychange is
185203 // always fired before pagehide) but older browsers may support
186204 // 'pagehide' but not 'visibilitychange'.
187- document . addEventListener (
188- 'pagehide' ,
189- this . config . useBeacon
190- ? this . dispatchBeaconFailSilent
191- : this . dispatchFetchFailSilent
192- ) ;
205+ document . addEventListener ( 'pagehide' , this . flushSync ) ;
193206 if ( this . config . dispatchInterval <= 0 || this . dispatchTimerId ) {
194207 return ;
195208 }
@@ -203,18 +216,8 @@ export class Dispatch {
203216 * Stop automatically dispatching cached events.
204217 */
205218 public stopDispatchTimer ( ) {
206- document . removeEventListener (
207- 'visibilitychange' ,
208- this . config . useBeacon
209- ? this . dispatchBeaconFailSilent
210- : this . dispatchFetchFailSilent
211- ) ;
212- document . removeEventListener (
213- 'pagehide' ,
214- this . config . useBeacon
215- ? this . dispatchBeaconFailSilent
216- : this . dispatchFetchFailSilent
217- ) ;
219+ document . removeEventListener ( 'visibilitychange' , this . flushSync ) ;
220+ document . removeEventListener ( 'pagehide' , this . flushSync ) ;
218221 if ( this . dispatchTimerId ) {
219222 window . clearInterval ( this . dispatchTimerId ) ;
220223 this . dispatchTimerId = undefined ;
0 commit comments