diff --git a/src/__tests__/posthog-core.test.ts b/src/__tests__/posthog-core.test.ts index 7b8047c56..cd18d1dd6 100644 --- a/src/__tests__/posthog-core.test.ts +++ b/src/__tests__/posthog-core.test.ts @@ -4,6 +4,7 @@ import { uuidv7 } from '../uuidv7' const mockReferrerGetter = jest.fn() const mockURLGetter = jest.fn() +const mockHostGetter = jest.fn() jest.mock('../utils/globals', () => { const orig = jest.requireActual('../utils/globals') return { @@ -22,6 +23,7 @@ jest.mock('../utils/globals', () => { const url = mockURLGetter?.() return { href: url, + host: mockHostGetter?.(), toString: () => url, } }, @@ -207,6 +209,27 @@ describe('posthog core', () => { expect(properties['$referrer']).toBe('$direct') expect(properties['$referring_domain']).toBe('$direct') }) + + it('should use $direct when the referrer is the same as the current host', () => { + // arrange + const token = uuidv7() + mockReferrerGetter.mockReturnValue('https://tracked.example.com') + mockHostGetter.mockReturnValue('tracked.example.com') + const { posthog, onCapture } = setup({ + token, + persistence_name: token, + }) + + // act + posthog.capture(eventName, eventProperties) + + // assert + const { $set_once, properties } = onCapture.mock.calls[0][1] + expect($set_once['$initial_referrer']).toBe('$direct') + expect($set_once['$initial_referring_domain']).toBe('$direct') + expect(properties['$referrer']).toBe('$direct') + expect(properties['$referring_domain']).toBe('$direct') + }) }) }) }) diff --git a/src/utils/event-utils.ts b/src/utils/event-utils.ts index cbca97de5..fd461c959 100644 --- a/src/utils/event-utils.ts +++ b/src/utils/event-utils.ts @@ -126,22 +126,27 @@ export const Info = { deviceType: detectDeviceType, - referrer: function (): string { - return document?.referrer || '$direct' + referrerInfo: function (): Record { + const referrer = document?.referrer + const referring_domain = referrer ? convertToURL(referrer)?.host : undefined + if (!referrer || !referring_domain || referring_domain === location?.host) { + return { + $referrer: '$direct', + $referring_domain: '$direct', + } + } + return { + $referrer: referrer, + $referring_domain: referring_domain, + } }, - referringDomain: function (): string { - if (!document?.referrer) { - return '$direct' - } - return convertToURL(document.referrer)?.host || '$direct' + referrer: function (): string { + return this.referrerInfo().$referrer }, - referrerInfo: function (): Record { - return { - $referrer: this.referrer(), - $referring_domain: this.referringDomain(), - } + referringDomain: function (): string { + return this.referrerInfo().$referring_domain }, initialPersonInfo: function (): Record {