client.web.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import type { AnalyticsClient } from './analytics.types';
  2. import { cleanUrl } from './privacy';
  3. type PrivacyNavigator = Navigator & { globalPrivacyControl?: boolean };
  4. /** False while rendering on the server: nothing is tracked there. */
  5. export function isClientAvailable(): boolean {
  6. return typeof window !== 'undefined' && typeof document !== 'undefined';
  7. }
  8. export function getClient(): AnalyticsClient {
  9. const screen = window.screen;
  10. return {
  11. platform: 'next-web',
  12. language: window.navigator.language || '',
  13. screen: screen ? `${screen.width}x${screen.height}` : '',
  14. };
  15. }
  16. /** The site's own origin, dropped from error sources and stack frames. */
  17. export function getOwnOrigin(): string {
  18. return window.location.origin;
  19. }
  20. /** The page an error or vitals hit belongs to: the address bar without its query string. */
  21. export function getHealthPageUrl(_viewUrl: string): string {
  22. const origin = window.location.origin;
  23. return origin + cleanUrl(window.location.href, origin);
  24. }
  25. /** The URL events are sent with before the first pageview. */
  26. export function getFallbackUrl(): string {
  27. return window.location.href;
  28. }
  29. /**
  30. * The referrer of the first page, only when it is another site: NEO's own host isn't one
  31. * of UNA's internal hosts, so a NEO page as referrer would count as a referral.
  32. */
  33. export function getInitialReferrer(): string {
  34. const referrer = document.referrer;
  35. if (!referrer) return '';
  36. try {
  37. return new URL(referrer).host !== window.location.host ? referrer : '';
  38. } catch {
  39. return '';
  40. }
  41. }
  42. /**
  43. * Don't track automated browsers, visitors who ask not to be tracked (Do Not Track, Global
  44. * Privacy Control) when the site honours it, and a browser excluded by hand with
  45. * `localStorage.setItem('bx_analytics_ignore', '1')`, as the classic tracker does.
  46. */
  47. export function isTrackingBlocked(respectDnt: boolean): boolean {
  48. const nav = window.navigator as PrivacyNavigator;
  49. if (nav.webdriver) return true;
  50. const windowDnt = (window as Window & { doNotTrack?: string }).doNotTrack;
  51. if (respectDnt && (nav.doNotTrack === '1' || windowDnt === '1' || nav.globalPrivacyControl === true)) return true;
  52. try {
  53. return window.localStorage.getItem('bx_analytics_ignore') === '1';
  54. } catch {
  55. return false;
  56. }
  57. }