Skip to content

JavaScript go to URL | Navigate to a new URL example

Use the assign() or replace() methods to lets the user go to a new URL. You can replace the current URL value to go to another URL In JavaScript.

JavaScript go to URL Examples

HTML examples code:

Assigning a new value to window.location

To navigate to a new URL, use the location object from the Browser’s History API.

Syntax

window.location = "url";

Complete code: will redirect us to a new URL

<!DOCTYPE HTML>
<html>

<body>

	<script>
		function goTo(){
			console.log("click")
			window.location = ('https://eyehunts.com') 
			console.log(window.location)
		}
		
		goTo();
	</script>
</body>
</html>					

Using the window.assign() method

The assign method assigns the current URL with the assigned URL and adds it to the history stack.

window.location.assign('https://eyehunts.com');

Using the window.replace() method

Using the replace() method, you can navigate a user to a site and stop them from going back to the previous page.

window.location.replace('https://eyehunts.com');

Output: For all examples

JavaScript go to URL new URL example

Do comment if you have any doubts and suggestions on this JS URL topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “JavaScript go to URL | Navigate to a new URL example”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading