How to redirect to another web page/ website using JavaScript

featured Image

In this short tutorial, we will learn different ways to redirect to another webpage / website using JavaScript.

Sometimes we want to redirect a user from the current page to a new page, for example whenever a user sign-in or logout from a page.

In JavaScript, we can redirect to a different webpage/ site using the window.location object.

The window.location object returns the current location of the document or to re-direct from one web page to another.

The window object is at the top of the scope chain, so instead of writing window.location.href, we can just use location.href .

Now let’s check how we can use this location property to redirect to another page using Javascript.

Redirect to a new URL using JavaScript.

To redirect to a new URL we can use the location object in our script.

We can use the href property with the location object to navigate to the new page or website.

location.href = 'www.google.com'

We just have to assign a value to the href property. Also, we can use the assign()method with the location object.

location.assign('www.google.com')

Both approaches will redirect you to the new URL and create an entry in the history stack of the browser.

Creating an entry in the history stack means that whenever we click the Back button it will take us to the previous page we have visited.

Now, if you don’t want to create a history stack while redirecting to another page or URL, then we can use the replace() method of the location object.

location.replace('www.google.com')

Redirect to relative Url on the website

To redirect to a page that is on the same root directory of the website, we can use the href property.

location.href = '/about.html'

HTML page redirect on page load using JavaScript

To redirect to a different page on page loading we can use the window.onload property along with the href property of the window object.

window.onload = function(){
    location.href = 'www.google.com'
}

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more