The Window.location read-only property returns a Location object with information about the current location of the document.
Before understanding how to access the entire URL or its components, let’s have a look at a basic URL structure:
- protocol - the name of protocol used to access the resource on the Internet. (HTTP, HTTPS, FTP, etc)
- hostname - the host that owns the resource.
- 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 (most HTTP URLs omit the port number).
- pathname - the specific resource in the host that the web client wants to access.
- query - 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 (#).
Use the following Location object properties to access the entire URL or its components.
- window.location.href - to get the entire URL
- window.location.host - to get the hostname and port of the URL
- window.location.hostname - to get the hostname of the URL
- window.location.protocol - to get the protocol of the URL in address bar
- window.location.pathname- to get the path and filename of the current page
- window.location.search - to get the query portion of the URL
- window.location.hash- to get the anchor portion of the URL
Use window.location.href property to get the entire URL of the current page:
<html> <head> <title>Title of the document</title> </head> <body> <p id="href"></p> <script> document.getElementById("href").innerHTML = "The full URL of this page is:<br>" + window.location.href; </script> </body> </html>