How to use location.replace() to redirect to another webpage In Javascript
The DOM Location replace() Method in HTML is used to replace the current document with the specified one. This method is different from the assign() method as this removes the current document from the document history, therefore it is not possible to go back to the previous document using the ‘back’ button.
Syntax:
location.replace("URL");
Example : In this example we contains a button triggering a JavaScript function. When clicked, it invokes location.replace() to redirect the user to the w3wiki website.
<!DOCTYPE html>
<html>
<body>
<h2>Welcome to w3wiki</h2>
<p>This is the example of <i>location.replace</i> method. </p>
<button onclick="myFunc()">Click me</button>
<!--script to redirect to another webpage-->
<script>
function myFunc() {
location.replace("https://www.w3wiki.org/");
}
</script>
</body>
</html>
Output:
Redirect to another webpage using JavaScript
Redirecting to another webpage using JavaScript enables dynamic navigation within web applications. By manipulating the window.location object, specifically its href property, developers can seamlessly guide users to different URLs based on various conditions or user interactions, enhancing user experience and application functionality.
Below are the methods used to redirect to another webpage using JavaScript:
Table of Content
- Using location.href
- Using location.replace()
Contact Us