js如何匹配域名
2024-02-15 17:09:10
關(guān)于JS(JavaScript)匹配域名的問(wèn)題的理解是,使用JavaScript中的URLSearchParams接口和window.location對(duì)象來(lái)實(shí)現(xiàn)。通過(guò)new URL(url)創(chuàng)建個(gè)URL對(duì)象,通過(guò)URLSearchParams對(duì)象獲取查詢字符串,使用window.location.href獲取當(dāng)前頁(yè)面的URL。這樣就通過(guò)比較這兩個(gè)值來(lái)判斷是否為同個(gè)域名了。
```javascript
var url = new URL('http://www.example.com/path?name=value');
var params = new URLSearchParams(url.search);
var currentUrl = window.location.href;
if (params.toString() === currentUrl) {
console.log('Same domain');
} else {
console.log('Different domain');
}
```