技术

前端生成uuid

注意点:http协议下无法使用crypto

前端生成唯一标识uuid

uuid是一个字符串,用于标记,v4版本的uuid只有极小的概率产生碰撞

//crypto.randomUUID()
const balabala = crypto.randomUUID() 
//生成的是第四代uuid

Can I Use?

参考链接:

https://developer.mozilla.org/zh-CN/docs/Web/API/Crypto/randomUUID https://developer.mozilla.org/zh-CN/docs/Glossary/UUID

注意点

http协议下无法使用crypto,浏览器认为不安全,直接拦截了,对于私有化部署的服务(可能会使用http),需要使用其他方法生成uuid

解决思路

首先判断协议,如果是https,那么沿用crypto生成uuid,如果是http或者不安全协议,那么使用date+mathrandom转16进制+拼接字符串

let sessionId: string;
if (window.isSecureContext) {
    sessionId = crypto.randomUUID();
} else {
    sessionId = Date.now().toString(16) + '-' + Math.random().toString(16).substring(2, 15);
}

export { sessionId };