Document

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.

Читайте также:  Javascript add canvas to canvas

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

  • Beginner Guide
    • Define Global Variable
    • Working with Object Literals
    • Working with Template Literals
    • Classes Overview
    • Subclass Examples
    • Iterators and Generators
    • Error Handling
    • Date Formatting
    • parseFloat()
    • Array.pop()
    • Array.slice()
    • Array.unshift()
    • Array.join()
    • Array.findIndex()
    • Array Slicing Methods
    • Remove Element from Array
    • Check Array is Empty
    • Create Unique Array of Objects
    • Convert Array to String
    • String.toLowerCase()
    • String.toString()
    • String.trimEnd()
    • String.trim()
    • String.replaceAll()
    • String.startsWith()
    • replaceWith()
    • String.indexOf()
    • replaceAll() with regex
    • Check if String is Number
    • Check string contains spaces
    • Convert String to Boolean
    • Check String contains Substring
    • Compare Strings
    • Math.acos()
    • Math.abs()
    • Math.asin()
    • Math.atan()
    • Math.cbrt()
    • Math.ceil()
    • Math.cos()
    • Math.floor()
    • Math.fround()
    • Math.hypot()
    • Math.log()
    • Math max()
    • Math.power()
    • Math.random()
    • Math.toRadians()
    • Nested Function
    • Arrow Function
    • Optional Parameters
    • The arguments Object
    • Calling Vs Invoking a Function
    • Call a function every second
    • Using function as Values
    • Chaining Functions
    • if statement
    • Handling Special Characters
    • hide() Method
    • Set.add()
    • Remove Element from Set
    • DOM Selector Methods
    • Find Elements in DOM
    • Remove DOM Element
    • Replace DOM Element
    • Get DOM Element Width
    • addEventListener()
    • querySelector()
    • getBoundingClientRect()
    • NodeList
    • Node.insertBefore()
    • Event Bubbling
    • Parse JSON File
    • Parse YAML File
    • Parse CSV File
    • async function
    • await
    • Exponentiation (**)
    • Bitwise XOR (^)
    • Nullish Coalescing Operator (??)
    • Double Exclamation Mark (!!)
    • Spread Operator (. )
    • Destructuring assignment
    • instanceof Operator
    • Access map with index
    • Check map size
    • Sort map by value
    • Sort by date
    • Add days to date
    • date/time field value out of range
    • Promise Thenable Object
    • Promise.all()
    • Promise.resolve()
    • Promise.race()
    • Promise.reject()
    • Chaining Promises
    • Keyboard Events
    • Mouse Events
    • Singleton Pattern
    • Mediator Pattern
    • Observer Pattern
    • Factory Pattern

    Источник

    Location.replace()

    Метод Location.replace() заменяет текущий ресурс на новый по URL, указанному в качестве параметра. Отличие от assign() в том, что при использовании replace() текущая страница не будет сохранена в History , и пользователь не сможет использовать кнопку назад, чтобы вернуться к ней.

    Если условия вызова метода не удовлетворяют требованиям безопасности, выбрасывается DOMException (en-US) с типом SECURITY_ERROR . Это случается, если домен скрипта, вызывающего метод, не совпадает с доменом страницы, изначально содержащимся в Location .

    Если новый URL некорректен, выбрасывается DOMException (en-US) с типом SYNTAX_ERROR .

    Синтаксис

    Параметры

    DOMString , содержащий URL страницы, на которую нужно перейти.

    Примеры

    // Перейти на статью Location.reload, заменив текущую страницу document.location.replace('https://developer.mozilla.org/ru/docs/Web/API/Location.reload'); 

    Спецификации

    Совместимость с браузерами

    BCD tables only load in the browser

    Смотрите также

    Found a content problem with this page?

    This page was last modified on 17 июл. 2023 г. by MDN contributors.

    Your blueprint for a better internet.

    MDN

    Support

    Our communities

    Developers

    Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
    Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

    Источник

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