跳到主要内容

认识

2023年11月06日
柏拉文
越努力,越幸运

一、认识


URL 接口用于解析,构造,规范化和编码 URL

二、语法


通过 URL() 构造函数创建 url 对象

const url = new URL("http://bolawen.com?a=1&b=2&c=3");
console.log(url);

三、Polyfill


function supportsURL() {
return typeof URL !== "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,
};
}
}