简体   繁体   English

在 JavaScript 中确定 URL 是否属于当前域的最佳方法是什么?

[英]What is the best way to determine if a URL belongs to the current domain in JavaScript?

I have a URL.我有一个网址。 It might be relative (eg not start with https://, etc.), or it might not be (starts with https://, etc.).它可能是相对的(例如不以 https:// 等开头),也可能不是(以 https:// 等开头)。

How can I determine if this URL refers to the same domain as window.location?如何确定此 URL 是否与 window.location 指向同一域?

(I'm creating a XMLHttpRequest and adding a cookie to it. Can only add the cookie if the URL I'm requesting is the same as the one I'm at. It's a secret cookie.) (我正在创建一个 XMLHttpRequest 并向其添加一个 cookie。如果我请求的 URL 与我所在的 URL 相同,则只能添加 cookie。这是一个秘密 cookie。)

The simplest way is actually to leverage the DOM: when you insert a URL into an <a> tag, the browser will actually resolve the URL immediately—ie when you retrieve the element's href attribute using JS, it will return an absolute path.最简单的方法实际上是利用 DOM:当您将 URL 插入<a>标签时,浏览器实际上会立即解析该 URL——即,当您使用 JS 检索元素的href属性时,它将返回一个绝对路径。

Then, you can simply check if the resolved path contains window.location.origin :然后,您可以简单地检查解析的路径是否包含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

For a ES5-compliant version, swap String.prototype.includes with String.prototype.indexOf :对于符合 ES5 的版本,将String.prototype.includesString.prototype.indexOf交换:

return link.href.indexOf(window.location.origin) !== -1;

Also, if your browser does not support window.location.origin , you will need to construct it manually:此外,如果您的浏览器不支持window.location.origin ,您将需要手动构建它:

var origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');

...therefore, the IE11-compatible version (if IE11 support is absolutely needed), will be as follow: ...因此,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM