Home >Web Front-end >JS Tutorial >How to Redirect to a Page Using JavaScript?

How to Redirect to a Page Using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-12 11:20:02592browse

How to Redirect to a Page Using JavaScript?

How to Redirect to a Page Using JavaScript

JavaScript provides a simple way to redirect users to a different page from the current page. To achieve this, you can utilize the window.location property.

Redirect with JavaScript

To redirect to another page, follow these steps:

1. Set the window.location property to the target URL:

window.location = "http://www.yoururl.com";

This line of code will immediately redirect the user to the specified URL.

Example:

window.location.href = "https://example.com"; // Redirect to "example.com"
window.location.assign("https://example.org"); // Also redirect to "example.org"
window.location.replace("https://example.net"); // Replaces the current page with "example.net"

Note:

  • Ensure that the target URL is a valid and accessible URL.
  • The code executes immediately, so there's no need to explicitly call any methods.
  • You can also use the window.location.replace() method to perform a redirect. However, this method replaces the current page in the history stack, meaning users cannot use the "back" button to return to the original page.

The above is the detailed content of How to Redirect to a Page Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn