HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Check if two URLs are on the same origin

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptsameurlschecktwoorigintheare

Problem

Two URLs are considered to be on the same origin if they have the same protocol, host, and port. This is an important concept in web security, as it determines whether a web page can access resources from another page.
In order to determine if two URLs are on the same origin, we can easily use URL.protocol, URL.host, and URL.port to compare the properties of the two URLs. If all three properties match, the URLs are on the same origin. Otherwise, they are not.

Solution

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

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

Code Snippets

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

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

Context

From 30-seconds-of-code: is-same-origin

Revisions (0)

No revisions yet.