DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info

2

How to Redirect to Another Webpage in JavaScript?

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

Redirecting to another webpage is a common operation we do in JavaScript programs.

In this article, we’ll look at how to redirect to a given URL with JavaScript.

window.location.replace

One way to redirect to a given URL is to use the window.location.replace method.

For instance, we can write:

window.location.replace('https://yahoo.com')
Enter fullscreen mode Exit fullscreen mode

We just pass in the URL in there.

replace doesn’t keep a record in the session history.

We can omit window since window is the global object:

location.replace('https://yahoo.com')
Enter fullscreen mode Exit fullscreen mode

window.location.href

We can also set the window.location.href property to the URL we want to go to.

For instance, we can write:

window.location.href = 'https://yahoo.com'
Enter fullscreen mode Exit fullscreen mode

Setting window.location.href adds a record to the browser history, which is the same as clicking on a link.

Also, we can shorten this to location.href since window is global:

location.href = 'https://yahoo.com'
Enter fullscreen mode Exit fullscreen mode

window.location.assign

Also, we can call window.location.assign to navigate to the URL we want.

For instance, we can write:

window.location.assign('https://yahoo.com')
Enter fullscreen mode Exit fullscreen mode

To navigate to ‘https://yahoo.com' .

It also keeps a record in the browser history.

We can shorten this to location.assign since window is the global object:

location.assign('https://yahoo.com')
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are a few ways to navigate to a URL in our JavaScript app.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post