Skip to content

Commit

Permalink
Update fetch instrumentation to be runtime agnostic (#4063)
Browse files Browse the repository at this point in the history
Co-authored-by: Marc Pichler <marc.pichler@dynatrace.com>
  • Loading branch information
drewcorlin1 and pichlermarc committed Nov 15, 2023
1 parent 10f6c46 commit 5ed54c8
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -20,6 +20,7 @@ For experimental package changes, see the [experimental CHANGELOG](experimental/

### :bug: (Bug Fix)

* fix(sdk-trace-web): only access location if it is defined [#4063](https://github.com/open-telemetry/opentelemetry-js/pull/4063)
* fix(sdk-trace-base): processor onStart called with a span having empty attributes

## 1.18.1
Expand Down
2 changes: 2 additions & 0 deletions experimental/CHANGELOG.md
Expand Up @@ -11,6 +11,8 @@ All notable changes to experimental packages in this project will be documented
### :bug: (Bug Fix)

* fix(sdk-logs): avoid map attribute set when count limit exceeded
* fix(instrumentation-fetch): only access navigator if it is defined [#4063](https://github.com/open-telemetry/opentelemetry-js/pull/4063)
* allows for experimental usage of this instrumentation with non-browser runtimes

### :books: (Refine Doc)

Expand Down
Expand Up @@ -132,7 +132,12 @@ export class FetchInstrumentation extends InstrumentationBase<
SemanticAttributes.HTTP_SCHEME,
parsedUrl.protocol.replace(':', '')
);
span.setAttribute(SemanticAttributes.HTTP_USER_AGENT, navigator.userAgent);
if (typeof navigator !== 'undefined') {
span.setAttribute(
SemanticAttributes.HTTP_USER_AGENT,
navigator.userAgent
);
}
}

/**
Expand Down
9 changes: 7 additions & 2 deletions packages/opentelemetry-sdk-trace-web/src/utils.ts
Expand Up @@ -131,6 +131,11 @@ export function sortResources(
});
}

/** Returns the origin if present (if in browser context). */
function getOrigin(): string | undefined {
return typeof location !== 'undefined' ? location.origin : undefined;
}

/**
* Get closest performance resource ignoring the resources that have been
* already used.
Expand Down Expand Up @@ -174,7 +179,7 @@ export function getResource(
}
const sorted = sortResources(filteredResources);

if (parsedSpanUrl.origin !== location.origin && sorted.length > 1) {
if (parsedSpanUrl.origin !== getOrigin() && sorted.length > 1) {
let corsPreFlightRequest: PerformanceResourceTiming | undefined = sorted[0];
let mainRequest: PerformanceResourceTiming = findMainRequest(
sorted,
Expand Down Expand Up @@ -438,7 +443,7 @@ export function shouldPropagateTraceHeaders(
}
const parsedSpanUrl = parseUrl(spanUrl);

if (parsedSpanUrl.origin === location.origin) {
if (parsedSpanUrl.origin === getOrigin()) {
return true;
} else {
return propagateTraceHeaderUrls.some(propagateTraceHeaderUrl =>
Expand Down

0 comments on commit 5ed54c8

Please sign in to comment.