@@ -232,17 +232,28 @@ export function shouldAttachHeaders(
232
232
targetUrl : string ,
233
233
tracePropagationTargets : ( string | RegExp ) [ ] | undefined ,
234
234
) : boolean {
235
- const resolvedUrl = new URL ( targetUrl , WINDOW . location . origin ) ;
236
- const isSameOriginRequest = resolvedUrl . origin === WINDOW . location . origin ;
237
-
238
- if ( ! tracePropagationTargets ) {
239
- return isSameOriginRequest ;
235
+ // window.location.origin not being defined is an edge case in the browser but we need to handle it.
236
+ // Potentially dangerous situations where it may not be defined: Browser Extensions, Web Workers, patching of the location obj
237
+ const origin : string | undefined = WINDOW . location && WINDOW . location . origin ;
238
+
239
+ if ( ! origin ) {
240
+ // If there is no window.location.origin, we default to only attaching tracing headers to relative requests, i.e. ones that start with `/`
241
+ // BIG DISCLAIMER: Users can call URLs with a double slash (fetch("//example.com/api")), this is a shorthand for "send to the same protocol",
242
+ // so we need a to exclude those requests, because they might be cross origin.
243
+ const isRelativeSameOriginRequest = ! ! targetUrl . match ( / ^ \/ (? ! \/ ) / ) ;
244
+ if ( ! tracePropagationTargets ) {
245
+ return isRelativeSameOriginRequest ;
246
+ } else {
247
+ return stringMatchesSomePattern ( targetUrl , tracePropagationTargets ) ;
248
+ }
249
+ } else {
250
+ const resolvedUrl = new URL ( targetUrl , origin ) ;
251
+ const isSameOriginRequest = resolvedUrl . origin === WINDOW . location . origin ;
252
+ return (
253
+ stringMatchesSomePattern ( resolvedUrl . toString ( ) , tracePropagationTargets ) ||
254
+ ( isSameOriginRequest && stringMatchesSomePattern ( resolvedUrl . pathname , tracePropagationTargets ) )
255
+ ) ;
240
256
}
241
-
242
- return (
243
- stringMatchesSomePattern ( resolvedUrl . toString ( ) , tracePropagationTargets ) ||
244
- ( isSameOriginRequest && stringMatchesSomePattern ( resolvedUrl . pathname , tracePropagationTargets ) )
245
- ) ;
246
257
}
247
258
248
259
/**
0 commit comments