Same-origin URLs

Angelos Chalaris · JavaScript, Object · Apr 22, 2021

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

Recommended snippets

  • Check object equality

    JavaScript, Object

    Performs a deep comparison between two values to determine if they are equivalent.

  • Deep merge objects

    JavaScript, Object

    Deeply merges two objects, using a function to handle keys present in both.

  • Query string to object

    JavaScript, Object

    Generates an object from the given query string or URL.