JavaScript – Page Redirection

By Published 2 min read

Page redirection is a web development technique that involves automatically sending a website visitor from one web page to another. It’s a way to navigate users to a different URL or web page, often used for various purposes such as:

  1. User Navigation: Redirecting users to the correct page when they enter a website or click on links. For example, after logging in, a user might be redirected to their dashboard.
  2. Form Submission: After a user submits a form, redirection can be used to show a confirmation message on a separate page or take them to a thank-you page.
  3. URL Changes: Handling changes in URL structure or moving content to a new location. Redirection ensures that old links or bookmarks still work.
  4. Authentication: For login or authentication purposes, users may be redirected to a login page and then back to the original page after authentication.
  5. SEO and Site Maintenance: Managing SEO by setting up proper redirects for changed or outdated URLs to maintain search engine rankings.

Page redirection is achieved through code, often using JavaScript or server-side scripting languages like PHP or Python. It’s a valuable tool for improving user experience, website maintenance, and managing content transitions.

Here’s how you can perform page redirection using JavaScript:

// Using the window.location object to redirect
function redirectToPage() {
    // Replace 'newPage.html' with the URL of the page you want to redirect to
    window.location.href = 'newPage.html';
}

// Call the redirectToPage function to trigger the redirection
redirectToPage();Code language: JavaScript (javascript)

In this example:

  1. We define a JavaScript function called redirectToPage().
  2. Inside the function, we use window.location.href to set the new URL. Replace 'newPage.html' with the URL of the page you want to redirect to.
  3. Finally, we call the redirectToPage() function to initiate the redirection.

Keep in mind that page redirection can also be triggered by user interactions (e.g., clicking a button) or conditions (e.g., based on the result of an operation). It’s a powerful tool for creating dynamic and interactive web experiences.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume