gongxiangp2/lib/browser-uuid.ts

11 lines
646 B
TypeScript

/** Crypto.getRandomValues is also available on the platform's HTTP LAN origin. */
export function createBrowserUuid(): string {
const cryptoApi = globalThis.crypto
if (typeof cryptoApi?.getRandomValues !== 'function') throw new Error('当前浏览器无法生成请求编号,请更新浏览器后再试')
const bytes = cryptoApi.getRandomValues(new Uint8Array(16))
bytes[6] = (bytes[6] & 0x0f) | 0x40
bytes[8] = (bytes[8] & 0x3f) | 0x80
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}