Document

How to redirect to another web page using JavaScript

JavaScript offers many ways to redirect the user to a different web page, if during the execution of your program you need to move to a different page.

The one that can be considered canonical to navigate to a new URL is

window.location = 'https://newurl.com'

If you want to redirect to a different path, on the same domain, use:

window.location.pathname = '/new'

This is using the location object offered by the History API.

Other options to redirect

As with most things in programming, there are many ways to perform the same operation.

Since window is implicit in the browser, you can also do:

Another way is to set the href property of location :

window.location.href = 'https://newurl.com'

location also has an assign() method that accepts a URL, and performs the same thing:

window.location.assign('https://newurl.com')

The replace() method is different than the previous ways because it rewrites the current page in the history. The current page is wiped, so when you click the “back” button, you go back to the page that now is the last visited one.

window.location.replace('https://newurl.com')

This can be convenient in some situations.

Different ways to reach the window object

The browser exposes the self and top objects, which all reference the window object, so you can use them instead of window in all the examples above:

self.location = 'https://newurl.com' top.location = 'https://newurl.com'

301 redirect using a server-side directive

The above examples all consider the case of a programmatic decision to move away to a different page.

If you need to redirect because the current URL is old, and move the a new URL, it’s best to use server-level directive and set the 301 HTTP code to signal search engines that the current URL has permanently moved to the new resource.

This can be done via .htaccess if using Apache. Netlify does this through a _redirects file.

Are 301 redirects possible using JavaScript?

That’s not possible to do on the client-side.

The 301 HTTP response code must be sent from the server, well before the JavaScript is executed by the browser.

Experiments say that JavaScript redirects are interpreted by the search engines like 301 redirects. See this Search Engine Land post for reference.

Using JavaScript to redirect users can be a legitimate practice. For example, if you redirect users to an internal page once they’re logged in, you can use JavaScript to do so. When examining JavaScript or other redirect methods to ensure your site adheres to our guidelines, consider the intent. Keep in mind that 301 redirects are best when moving your site, but you could use a JavaScript redirect for this purpose if you don’t have access to your website’s server.

Use an HTML meta tag

Another option is using a meta tag in your HTML:

html>  head>  meta http-equiv="refresh" content="0;URL=https://newurl.com/">  head> html>

This will cause the browser to load the new page once it has loaded and interpreted the current one, and not signal search engines anything. The best option is always to use a 301 server-level redirect.

Источник

How to redirect with JavaScript? [SOLVED]

You can do JavaScript redirection using the location object’s href attribute or assign() and replace() methods.

location.href = location.assign() location.replace()

This tutorial teaches you the origin, usage, and differences between the three ways: href , assign() and replace() .

Window and location objects

The window object is the root of the browser API. Other objects like location interact with your JavaScript through the window object.

window.location // OR location

The location object has information about the current URL. It enables you to interact with the current URL through its attributes and methods.

The location object has attributes like href , protocol , origin , host , hostname , port , and pathname .

/* < "ancestorOrigins": <>, "href": "http://127.0.0.1:5500/index.html", "origin": "http://127.0.0.1:5500", "protocol": "http:", "host": "127.0.0.1:5500", "hostname": "127.0.0.1", "port": "5500", "pathname": "/index.html", "search": "", "hash": "" > */

The href attribute creates a link to another page. You can use it for JavaScript redirection as shown in the examples section.

The location object also presents you with methods to achieve JavaScript redirection or page refresh.

assign() : Enables JavaScript redirection with the ability to click the back button to the previous page.

reload() : Refreshes the page with the browser’s cache (no parameter or false value) or data from the server (parameter is true ).

replace() : Achieves JavaScript redirection without the ability to click the back button to the previous page.

toString() : Stringifies a URL and then returns a string containing the whole URL.

3 typical ways to do redirection with JavaScript

You can do JavaScript redirection using the href attribute, the assign() method, or the replace() method.

The href attribute and the assign() method let you revert to the previous page in history through the browser’s back button. They do that by appending the new URL to the history stack. Use location.href or location.assign() to simulate the reader clicking on a link.

On the other hand, the replace() method does not append the URL to the history stack. So, you cannot return to the previous page through the back button. Use the location.replace() method to simulate the HTTP redirect.

Now that you understand when and how to use JavaScript redirection, let’s dive into practical examples.

Scenario-1: Redirect to a local URL with javaScript

Example~1: Button click to an absolute path

Assume we have index.html and about.html pages. We aim to redirect the user to the about.html by clicking a button with an option to return to the index.html throw the back button.

We attach a click event to the button. On clicking the button, the location.assign() method gets run.

We get redirected to about.html.

        

About page

Welcome to about page

JavaScript redirection using the assign method

Example~2: User redirection to login page

We can also apply JavaScript redirection to send the user to a login page after registration. For example, let’s register a user with the username, email, and password in the index.php page and then redirect them to the login.php page.

Before writing the registration code, we create the test database with the users table using PHPMyAdmin.

CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL, pwd VARCHAR(100) NOT NULL );

How to redirect with JavaScript? [SOLVED]

Next, we create the header.php and footer.php files.

Then, we import the header.php and the footer.php into the index.php and login.php files.

  

Register









How to redirect with JavaScript? [SOLVED]

We send the username, email, pwd, and pwd_conf to the PHP script implemented in the register.php file.

 0) < echo('  '); exit(); > // validataion_2: passwords not matching if($pwd !== $pwd_conf) < echo('  '); exit(); > //SAVING DETAILS INTO THE DATABASE $hashedPwd = password_hash($pwd, PASSWORD_BCRYPT); $new_user = mysqli_query($conn, "INSERT INTO users (username, email, pwd) VALUES ('$username', '$email', '$hashedPwd') "); if($new_user) < echo('  '); exit(); > >

First, we connect the application to the test database. When the user clicks on the register button, we grab form data and sanitize them. We then validate the username and the password.

If the username has been saved in the database, we let the user know their mistake before redirecting them to the registration (index.php) page.

$check = mysqli_query($conn, "SELECT * FROM users WHERE username='$username'"); if(mysqli_num_rows($check) > 0) < echo('  '); exit(); >

Similarly, we redirect the user to the index.php page if passwords don’t match.

if($pwd !== $pwd_conf) < echo('  '); exit(); >

Otherwise, we register the user with a hashed password and redirect them to the login.php page.

 $hashedPwd = password_hash($pwd, PASSWORD_BCRYPT); $new_user = mysqli_query($conn, "INSERT INTO users (username, email, pwd) VALUES ('$username', '$email', '$hashedPwd') "); if($new_user) < echo('  '); exit(); >

How to redirect with JavaScript? [SOLVED]

Scenario-2: Redirect to another website with JavaScript

Example~1: Using button click

Assume we want the user to visit the GoLinuxCloud website by clicking a button. We can do that using the location object’s replace() method.

This time we cannot return to the index.html through the back button.

Example~2: Automatic JavaScript redirection after a page load

Assume we want to redirect the user to the GoLinuxCloud website five seconds after the page load.

        

Redirecting to GoLinuxCloud in about 5 seconds

We invoke the window object’s onload function. The function then runs the setTimeout() function, which waits for 5000 milliseconds before redirecting the user to https://www.golinuxcloud.com using the location.replace() method.

Summary

Use location.href and location.assign() to do a JavaScript direction while retaining the back button to return to the previous page.

Alternatively, use the location.replace() method to redirect a user to a new page without the ability to return to the previous page through the back button.

Further Reading

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

JavaScript Tutorial

Оцените статью