30秒学会 JavaScript 片段 · 2023年1月26日

30秒学会 JavaScript 片段 – Same-origin URLs

Checks if two URLs are on the same origin.

  • Use URL.protocol and URL.host to check if both URLs have the same protocol and host.

代码实现

const isSameOrigin = (origin, destination) =>
  origin.protocol === destination.protocol && origin.host === destination.host;

const origin = new URL('https://www.30secondsofcode.org/about');
const destination = new URL('https://www.30secondsofcode.org/contact');
isSameOrigin(origin, destination); // true
const other = new URL('https://developer.mozilla.org);
isSameOrigin(origin, other); // false

翻译自:https://www.30secondsofcode.org/js/s/is-same-origin