应用场景
2023年11月06日
一、规范化 url
function supportsURL() {
return typeof URL !== "undefined";
}
function supportsSearchParams() {
return typeof URLSearchParams !== "undefined";
}
function normalizeUrl(url) {
if (supportsURL()) {
try {
const urlObj = new URL(url || window.location.href);
return {
href: urlObj.href,
protocol: urlObj.protocol,
host: urlObj.host,
hostname: urlObj.hostname,
port: urlObj.port,
pathname: urlObj.pathname,
search: urlObj.search,
hash: urlObj.hash,
};
} catch (error) {
return null;
}
} else {
const a = document.createElement("a");
a.href = url || window.location.href;
return {
href: a.href,
protocol: a.protocol,
host: a.host,
hostname: a.hostname,
port: a.port,
pathname: a.pathname,
search: a.search,
hash: a.hash,
};
}
}