( targetUrl: string, tracePropagationTargets: (string | RegExp)[] | undefined, )
| 279 | * We only export this function for testing purposes. |
| 280 | */ |
| 281 | export function shouldAttachHeaders( |
| 282 | targetUrl: string, |
| 283 | tracePropagationTargets: (string | RegExp)[] | undefined, |
| 284 | ): boolean { |
| 285 | // window.location.href not being defined is an edge case in the browser but we need to handle it. |
| 286 | // Potentially dangerous situations where it may not be defined: Browser Extensions, Web Workers, patching of the location obj |
| 287 | const href = getLocationHref(); |
| 288 | |
| 289 | if (!href) { |
| 290 | // If there is no window.location.origin, we default to only attaching tracing headers to relative requests, i.e. ones that start with `/` |
| 291 | // BIG DISCLAIMER: Users can call URLs with a double slash (fetch("//example.com/api")), this is a shorthand for "send to the same protocol", |
| 292 | // so we need a to exclude those requests, because they might be cross origin. |
| 293 | const isRelativeSameOriginRequest = !!targetUrl.match(/^\/(?!\/)/); |
| 294 | if (!tracePropagationTargets) { |
| 295 | return isRelativeSameOriginRequest; |
| 296 | } else { |
| 297 | return stringMatchesSomePattern(targetUrl, tracePropagationTargets); |
| 298 | } |
| 299 | } else { |
| 300 | let resolvedUrl; |
| 301 | let currentOrigin; |
| 302 | |
| 303 | // URL parsing may fail, we default to not attaching trace headers in that case. |
| 304 | try { |
| 305 | resolvedUrl = new URL(targetUrl, href); |
| 306 | currentOrigin = new URL(href).origin; |
| 307 | } catch { |
| 308 | return false; |
| 309 | } |
| 310 | |
| 311 | const isSameOriginRequest = resolvedUrl.origin === currentOrigin; |
| 312 | if (!tracePropagationTargets) { |
| 313 | return isSameOriginRequest; |
| 314 | } else { |
| 315 | return ( |
| 316 | stringMatchesSomePattern(resolvedUrl.toString(), tracePropagationTargets) || |
| 317 | (isSameOriginRequest && stringMatchesSomePattern(resolvedUrl.pathname, tracePropagationTargets)) |
| 318 | ); |
| 319 | } |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | /** |
| 324 | * Create and track xhr request spans |
no test coverage detected