JavaScript go to URL | Navigate to a new URL example

Use the assign() or replace() methods to lets user go to a new URL. You can replace 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

Assign method assigns the current URL with the assigned URL and add 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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.