js 实用函数

1、基于URL或者Crypto.getRandomValues生成UUID

export const genUuid = () => {
    const url = URL.createObjectURL(new Blob([]));
    const uuid = url.substring(url.lastIndexOf('/')+ 1);
    URL.revokeObjectURL(url);
    return uuid;
}
genUuid()
//"f2ccfca8-bcf4-4e2e-afdb-084c070f9505"

2、基于URLSearchParams或URL获取queryString的值

const urlSP = new URLSearchParams(location.search);
function getQueryString(key){
    return urlSP.get(key)
}
const urlObj = new URL(location.href);
function getQueryString(key){
    return urlObj.searchParams.get(key)
}
测试:XXX/index?type=100
console.log("type=", getQueryString("type"));  
输出:type=100

3、关闭页面时向后台发送消息

 window.addEventListener("beforeunload", (e) => {
    const data = {str: "关闭页面"};
    window.navigator.sendBeacon("http://127.0.0.1:8080/loginout", JSON.stringify(data));
});

你可能感兴趣的:(js 实用函数)