Checking Same-Origin URLs with JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/SecurityGroup(["`Security`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/SecurityGroup -.-> javascript/web_sec("`Web Security Basics`") subgraph Lab Skills javascript/variables -.-> lab-28441{{"`Checking Same-Origin URLs with JavaScript`"}} javascript/data_types -.-> lab-28441{{"`Checking Same-Origin URLs with JavaScript`"}} javascript/arith_ops -.-> lab-28441{{"`Checking Same-Origin URLs with JavaScript`"}} javascript/comp_ops -.-> lab-28441{{"`Checking Same-Origin URLs with JavaScript`"}} javascript/obj_manip -.-> lab-28441{{"`Checking Same-Origin URLs with JavaScript`"}} javascript/web_sec -.-> lab-28441{{"`Checking Same-Origin URLs with JavaScript`"}} end

Check if Two URLs are on the Same Origin

To check if two URLs are on the same origin:

  1. Open the Terminal/SSH and type node to start practicing coding.

  2. 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;
  1. 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");
  1. Call the isSameOrigin function with the two URL objects as arguments to get a boolean output.
isSameOrigin(origin, destination); // true
  1. 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.

Other JavaScript Tutorials you may like