[英]What is the best way to determine if a URL belongs to the current domain in JavaScript?
我有一個網址。 它可能是相對的(例如不以 https:// 等開頭),也可能不是(以 https:// 等開頭)。
如何確定此 URL 是否與 window.location 指向同一域?
(我正在創建一個 XMLHttpRequest 並向其添加一個 cookie。如果我請求的 URL 與我所在的 URL 相同,則只能添加 cookie。這是一個秘密 cookie。)
最簡單的方法實際上是利用 DOM:當您將 URL 插入<a>
標簽時,瀏覽器實際上會立即解析該 URL——即,當您使用 JS 檢索元素的href
屬性時,它將返回一個絕對路徑。
然后,您可以簡單地檢查解析的路徑是否包含window.location.origin
:
function doesUrlBelongsToCurrentDomain(url) { const link = document.createElement('a'); link.href = url; return link.href.includes(window.location.origin); } console.log(doesUrlBelongsToCurrentDomain('https://google.com')); // false console.log(doesUrlBelongsToCurrentDomain('./relative-link')); // true console.log(doesUrlBelongsToCurrentDomain('/relative-link')); // true
對於符合 ES5 的版本,將String.prototype.includes
與String.prototype.indexOf
交換:
return link.href.indexOf(window.location.origin) !== -1;
此外,如果您的瀏覽器不支持window.location.origin
,您將需要手動構建它:
var origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
...因此,IE11兼容版本(如果絕對需要IE11支持),將如下:
function doesUrlBelongsToCurrentDomain(url) {
var link = document.createElement('a');
link.href = url;
var origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
return link.href.indexOf(origin) !== -1;
}
您可以從要測試的 url 創建一個URL 對象,並將其與當前位置來源進行比較:
const sameOrigin = new URL('URL_TO_TEST').origin === window.location.origin;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.