Skip to content

URL Info Access | Accessing a URL via web browser JavaScript

  • by

JavaScript provides you with many methods to retrieve and change the current URL, which is displayed in the browser’s address bar. All these methods use the Location object, which is a property of the Window object. You can create a new Location an object that has the current URL as follows:

var currentLocation = window.location;

Basic URL Structure

<protocol>//<hostname>:<port>/<pathname><search><hash>
  • protocol: Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
  • hostname: Hostname specifies the host that owns the resource. For example, www.eyehunts.com. A server provides services using the name of the host.
  • port: A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
  • pathname: The path gives info about the specific resource within the host that the Web client wants to access. For example, /index.html.
  • search: A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
  • hash: The anchor portion of a URL, includes the hash sign (#).

With these Location object properties you can access all of these URL components and what they can set or return:

  • href – the entire URL
  • protocol – the protocol of the URL
  • host – the hostname and port of the URL
  • hostname – the hostname of the URL
  • port – the port number the server uses for the URL
  • pathname – the pathname of the URL
  • search – the query portion of the URL
  • hash – the anchor portion of the URL

HTML Example code Get URL

<!DOCTYPE HTML>
<html>

<body>

	<script>
		var currentLocation = window.location;
		alert(currentLocation);
	</script>
</body>
</html>					

Output

URL Info Access a URL via web browser JavaScript

Leave a Reply

Discover more from Tutorial

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

Continue reading