|
1 | 1 | import { describe, expect, it } from "vitest"; |
2 | 2 | import { isMobilePlatform } from "./platformPaths"; |
3 | 3 |
|
| 4 | +const globalScope = globalThis as typeof globalThis & { navigator?: Navigator }; |
| 5 | + |
4 | 6 | function withNavigatorValues( |
5 | 7 | values: Partial<Pick<Navigator, "platform" | "userAgent">>, |
6 | 8 | run: () => void, |
7 | 9 | ) { |
8 | | - const originalPlatform = Object.getOwnPropertyDescriptor(navigator, "platform"); |
9 | | - const originalUserAgent = Object.getOwnPropertyDescriptor(navigator, "userAgent"); |
10 | | - Object.defineProperty(navigator, "platform", { |
| 10 | + const hadNavigator = typeof globalScope.navigator !== "undefined"; |
| 11 | + if (!hadNavigator) { |
| 12 | + Object.defineProperty(globalScope, "navigator", { |
| 13 | + configurable: true, |
| 14 | + writable: true, |
| 15 | + value: {}, |
| 16 | + }); |
| 17 | + } |
| 18 | + |
| 19 | + const activeNavigator = globalScope.navigator as Navigator; |
| 20 | + const originalPlatform = Object.getOwnPropertyDescriptor(activeNavigator, "platform"); |
| 21 | + const originalUserAgent = Object.getOwnPropertyDescriptor(activeNavigator, "userAgent"); |
| 22 | + Object.defineProperty(activeNavigator, "platform", { |
11 | 23 | configurable: true, |
12 | | - value: values.platform ?? navigator.platform, |
| 24 | + value: values.platform ?? activeNavigator.platform ?? "", |
13 | 25 | }); |
14 | | - Object.defineProperty(navigator, "userAgent", { |
| 26 | + Object.defineProperty(activeNavigator, "userAgent", { |
15 | 27 | configurable: true, |
16 | | - value: values.userAgent ?? navigator.userAgent, |
| 28 | + value: values.userAgent ?? activeNavigator.userAgent ?? "", |
17 | 29 | }); |
18 | 30 | try { |
19 | 31 | run(); |
20 | 32 | } finally { |
21 | 33 | if (originalPlatform) { |
22 | | - Object.defineProperty(navigator, "platform", originalPlatform); |
| 34 | + Object.defineProperty(activeNavigator, "platform", originalPlatform); |
| 35 | + } else { |
| 36 | + delete (activeNavigator as { platform?: string }).platform; |
23 | 37 | } |
24 | 38 | if (originalUserAgent) { |
25 | | - Object.defineProperty(navigator, "userAgent", originalUserAgent); |
| 39 | + Object.defineProperty(activeNavigator, "userAgent", originalUserAgent); |
| 40 | + } else { |
| 41 | + delete (activeNavigator as { userAgent?: string }).userAgent; |
| 42 | + } |
| 43 | + if (!hadNavigator) { |
| 44 | + Reflect.deleteProperty(globalScope, "navigator"); |
26 | 45 | } |
27 | 46 | } |
28 | 47 | } |
|
0 commit comments