Introduction
In this lab, we will explore how to check if two URLs are on the same origin using JavaScript. We will use the URL.protocol and URL.host properties to compare the protocol and host of the URLs and determine whether they belong to the same origin or not. This is a useful skill for web developers who need to ensure the security of their web applications and prevent cross-site scripting attacks.
Check if Two URLs are on the Same Origin
To check if two URLs are on the same origin:
Open the Terminal/SSH and type
nodeto start practicing coding.Use
URL.protocolandURL.hostto check if both URLs have the same protocol and host.
const isSameOrigin = (origin, destination) =>
origin.protocol === destination.protocol && origin.host === destination.host;
- Create two URL objects with the URLs you want to compare.
const origin = new URL("https://www.30secondsofcode.org/about");
const destination = new URL("https://www.30secondsofcode.org/contact");
- Call the
isSameOriginfunction with the two URL objects as arguments to get a boolean output.
isSameOrigin(origin, destination); // true
- You can also test the function with other URLs to see if they are on the same origin or not.
const other = new URL("https://developer.mozilla.org");
isSameOrigin(origin, other); // false
Summary
Congratulations! You have completed the Same-Origin URLs lab. You can practice more labs in LabEx to improve your skills.