Cover Image for JavaScript redirect
140 views

JavaScript redirect

To redirect a user to a different web page using JavaScript, you can use the window.location object. Here are a few ways to accomplish a redirect:

  1. Using the assign() method:
JavaScript
window.location.assign("https://www.example.com");

This method assigns a new URL to the current window, effectively redirecting the user to the specified URL.

  1. Using the replace() method:
JavaScript
window.location.replace("https://www.example.com");

This method replaces the current URL in the browser’s history with the new URL. The user is redirected to the new URL without the ability to navigate back to the previous page.

  1. Directly modifying the href property:
JavaScript
window.location.href = "https://www.example.com";

Assigning a new URL directly to the href property of window.location also triggers a redirect.

All of the above methods will cause the browser to navigate to the specified URL, loading the new page and potentially leaving the current page. It’s important to note that once a redirect is triggered, the remaining code in the current script will not be executed.

Remember to include the full URL (including the protocol, e.g., “https://”) in the redirect target for reliable navigation.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS