@@ -159,6 +159,26 @@ export class Dispatch {
159
159
return this . dispatchBeacon ( ) . catch ( ( ) => { } ) ;
160
160
} ;
161
161
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
+
162
182
/**
163
183
* Automatically dispatch cached events.
164
184
*/
@@ -177,19 +197,12 @@ export class Dispatch {
177
197
//
178
198
// A third option is to send both, however this would increase
179
199
// bandwitch and require deduping server side.
180
- this . config . useBeacon
181
- ? this . dispatchBeaconFailSilent
182
- : this . dispatchFetchFailSilent
200
+ this . flushSync
183
201
) ;
184
202
// Using 'pagehide' is redundant most of the time (visibilitychange is
185
203
// always fired before pagehide) but older browsers may support
186
204
// '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 ) ;
193
206
if ( this . config . dispatchInterval <= 0 || this . dispatchTimerId ) {
194
207
return ;
195
208
}
@@ -203,18 +216,8 @@ export class Dispatch {
203
216
* Stop automatically dispatching cached events.
204
217
*/
205
218
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 ) ;
218
221
if ( this . dispatchTimerId ) {
219
222
window . clearInterval ( this . dispatchTimerId ) ;
220
223
this . dispatchTimerId = undefined ;
0 commit comments