JavaScript BOM Location Object

BOM - Location Object

Location :

We have talked about different objects in BOM hierarchy for accessing the history of URLs visited by the user or to know the properties of the browser. Now, if we want to programmatically refresh the current page or navigate to a new page which object shall we use?

BOM hierarchy has 'location' object for this. It contains information about the current URL in the browser window. The information can be accessed or manipulated using following properties and methods.

If this is the URL: http://localhost:8080/JS_Demos/myLocationFile.html, properties have following interpretation:

Property Description Example
href Contains entire URL as string location.href; //Returns localhost:8080/JS_Demos/myLocationFile.html
hostname Contains hostname part of URL local.hostname; //Returns localhost
port Contains port number associated with URL location.port; //Returns 8080
pathname Contains filename or path specified by object location.pathname; //Returns /JS_Demos/myLocationFile.html

'location' object gives following methods to reload current page or to navigate to new page:

Method Description Example
assign() Loads new HTML document location.assign('http://www.facebook.com'); //Opens facebook page
reload() Reloads current HTML document location.reload(); //Current document is reloaded

Demo :

CODE/PROGRAM/EXAMPLE
//HTML code
	<html>
	  <head>
	  </head>
	  <body>
		<h2> Location </h2>
		<input type='button' value='Refresh' onclick=“location.reload();”>
		<input type='button' value='FaceBook' onclick=“location.assign('http://www.facebook.com');”>
	  </body>
	</html>
CODE/PROGRAM/EXAMPLE
//JS code
	document.write("<br><br>" + "location.href: " + location.href);
	document.write("<br><br>" + "location.hostname: " + location.hostname);
	document.write("<br><br>" + "location.port: " + location.port);
	document.write("<br><br>" + "location.pathname: " + location.pathname);

Demo 2 :

CODE/PROGRAM/EXAMPLE
//HTML code
	<html>
	  <head>
	  </head>
	  <body style="background-color:lightblue;text-align:center">
		<center>
		  <h2>Dating App</h2>
		  <h4>Login form</h4>
		  <button onclick="validation();">Enter credentials</button>
		</center>
	  </body>
	</html>
CODE/PROGRAM/EXAMPLE
//JS code

	function validation() {
		var username = prompt('Enter name');
		var password = prompt('Enter password');
		var storedName = sessionStorage.getItem('user');
		if (username == storedName && username == password) {
			location.assign('Home.html');
		} else {
			alert('User is not authenticated');
		}
	}
#location_object_in_javascript #Location_Object_javascript,location_object_in_javascript_example #Location_Object_javascript_example

(New page will open, for Comment)

Not yet commented...