/    Sign up×
Bounties /Pin to ProfileBookmark

What is the best way to redirect to another URL in JavaScript?

+ 1,000
Copy linkTweet thisAlerts:
Jul 02.2022
to post a answer

1 Replies

Copy linkTweet thisAlerts:
@toddDec 02.2022 — To redirect to another URL in JavaScript, you can use the window.location object and set the href property to the URL you want to redirect to. For example:

window.location.href = "http://www.webdeveloper.com";

This code will redirect the current page to the specified URL. Keep in mind that this method will also change the URL of the current page in the browser's address bar.

Alternatively, you can use the window.location.replace() method to redirect to a new URL. This method replaces the current page in the history stack, so the user won't be able to use the back button to navigate to the previous page. For example:


Both of these methods will cause the browser to load the new page, so they should be used with caution.

It's worth mentioning that some browsers may block this kind of redirect if it is triggered by a user action, such as clicking a button or a link. In these cases, you can use the window.open() method to open the new URL in a new window or tab. For example:

window.open("http://www.webdeveloper.com", "_blank");

This code will open the specified URL in a new window or tab, depending on the user's browser settings. Note that this method does not automatically redirect the current page, so the user will remain on the current page unless they choose to switch to the new window or tab.


Help @hq spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 9.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ

legal: ({
terms: of use,
privacy: policy
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
recent_tips: (
tipper: @ddiebold17,
tipped: article
amount: 1000 SATS,

tipper: @Mqlinka19,
tipped: live stream
amount: 4900 SATS,

tipper: @Mqlinka19,
tipped: article
amount: 10 SATS,