Skip to content

Commit 33ecd22

Browse files
author
Luca Forstner
committed
Handle window.location.origin being undefined
1 parent 946d35b commit 33ecd22

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

packages/tracing-internal/src/browser/request.ts

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -232,17 +232,28 @@ export function shouldAttachHeaders(
232232
targetUrl: string,
233233
tracePropagationTargets: (string | RegExp)[] | undefined,
234234
): 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+
);
240256
}
241-
242-
return (
243-
stringMatchesSomePattern(resolvedUrl.toString(), tracePropagationTargets) ||
244-
(isSameOriginRequest && stringMatchesSomePattern(resolvedUrl.pathname, tracePropagationTargets))
245-
);
246257
}
247258

248259
/**

0 commit comments

Comments
 (0)