Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Get Browser to Navigate URL in JavaScript?
Next article icon

How to redirect to a relative URL in JavaScript?

Last Updated : 30 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To redirect to a relative URL in JavaScript, you could use window.location.href. It is a property in JavaScript that represents the complete URL of the current page. It can be used to get the current URL or to navigate to a new URL by assigning a new URL to it.

Approach

  1. HTML Structure:
    • The HTML file includes a simple button with the text “Redirect.” When the button is clicked, it triggers the redirectToRelativeURL function.
  2. JavaScript Function (redirectToRelativeURL):
    • The redirectToRelativeURL function is defined in the <script> tag.
    • It begins by specifying the relative URL ('geeksforgeeks.org') to which the page should redirect.
  3. Construct Absolute URL:
    • The function uses the URL object to construct an absolute URL based on the current location (window.location.href) and the specified relative URL.
    • The URL object takes care of handling relative paths and ensures the resulting URL is valid.
  4. Redirect:
    • Finally, the function sets window.location.href to the constructed absolute URL, causing the browser to navigate to the specified location.

Example: Below is the implementation.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Redirect Example</title>
</head>
 
<body>
    <h2>Redirect Example</h2>
    <button onclick="redirectToRelativeURL()">Redirect</button>
 
    <script>
        // Function to redirect to a relative URL
        function redirectToRelativeURL() {
            // Relative URL to redirect to
            const relativeURL =
'https://www.geeksforgeeks.org/';
            // Construct absolute URL based
            // on the current location
            const absoluteURL =
            new URL(relativeURL, window.location.href);
 
            // Log the absolute URL (optional)
            console.log('Redirecting to:', absoluteURL.href);
 
            // Redirect to the absolute URL
            window.location.href = absoluteURL.href;
        }
    </script>
</body>
 
</html>
 
 

Output:

gfg



Next Article
How to Get Browser to Navigate URL in JavaScript?

D

divyanksingh200
Improve
Article Tags :
  • JavaScript
  • Technical Scripter
  • Web Technologies
  • JavaScript-Questions
  • Technical Scripter 2019

Similar Reads

  • How to add a parameter to the URL in JavaScript ?
    Given a URL the task is to add parameter (name & value) to the URL using JavaScript. URL.searchParams: This read-only property of the URL interface returns a URLSearchParams object providing access to the GET-decoded query arguments in the URL. Table of Content Using the append methodUsing set m
    2 min read
  • How to Get Browser to Navigate URL in JavaScript?
    As a web developer, you may need to navigate to a specific URL from your JavaScript code. This can be done by accessing the browser's window object and using one of the available methods for changing the current URL. In JavaScript, there are several approaches for navigating to a URL. The most commo
    4 min read
  • JavaScript Redirect a URL
    Redirecting a URL in JavaScript is nothing but sending the user from a URL to another URL. In Javascript, window.location function is used to redirect to a URL. Example 1: [GFGTABS] HTML <!DOCTYPE html> <html> <head> <title>Redirect url in Javascript</title> </head
    1 min read
  • How to redirect back to original URL in Node.js ?
    Node.js with the help of Express, supports web page routing. This means that when the client makes different requests, the application is routed to different web pages depending upon the request made and the routing methods defined. To learn more about Node.js routing and its implementation, refer t
    3 min read
  • How to Redirect to Another Webpage using JavaScript?
    JavaScript can redirects the users from current page to another webpage (different URL) with and without requiring any manual action (like clicking a link). To redirect to another weboage in JavaScript we need to manipulate the window.location object and it will allow us to navigate programmatically
    2 min read
  • How To Get URL And URL Parts In JavaScript?
    In web development, working with URLs is a common task. Whether we need to extract parts of a URL or manipulate the URL for navigation, JavaScript provides multiple approaches to access and modify URL parts. we will explore different approaches to retrieve the full URL and its various components. Th
    3 min read
  • How to Open URL in New Tab using JavaScript?
    HTML anchor tag is used to open URLs in a new tab using the target="_blank" attribute. In JavaScript, we have an inbuilt method window.open() which is used to open a new browser window or new tab depending on the browser settings. Using window.open() MethodTo open a new tab, we have to use _blank in
    2 min read
  • How to simulate target=“_blank” in JavaScript ?
    In web development, the target="_blank" attribute on anchor (<a>) tags is used to open links in a new browser tab or window. Sometimes, developers might need to achieve this behavior programmatically using JavaScript. Understanding these techniques equips developers with flexible solutions for
    2 min read
  • How to navigate URL in an iframe with JavaScript ?
    To navigate the URL in an iframe with JavaScript, we have to set the src attribute or return the value of the src attribute in an iframe element. The src attribute defines the URL of the document that can be shown in an iframe. Syntax:document.getElementById("selector").src = "URL";URL values: Absol
    1 min read
  • How to set location and location.href using JavaScript ?
    In this article, we will set the location and location.href using Javascript. Both location and location.href are used to set or return the complete URL of your current page. They return a string that contains the entire URL with the protocol. Syntax: location = "https://www.geeksforgeeks.org";or lo
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences