Fix UUID generation in browsers without crypto.randomUUID
This commit is contained in:
1 parent
b312a50d37
commit
9dd425f765
5 files changed
+172
No files matched your search
@@ -0,0 +1,18 @@
|
||||
// randomUUID is secure-context-only; getRandomValues is also available on HTTP.
|
||||
// Keep native implementations and never fall back to Math.random for IDs.
|
||||
(() => {
|
||||
'use strict';
|
||||
const crypto = globalThis.crypto;
|
||||
if (!crypto || typeof crypto.randomUUID === 'function' || typeof crypto.getRandomValues !== 'function') return;
|
||||
Object.defineProperty(crypto, 'randomUUID', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: function randomUUID() {
|
||||
const bytes = crypto.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)}`;
|
||||
},
|
||||
});
|
||||
})();
|
||||
Reference in new issue
Block a user