- All these methods uses the Location object, which is a property of the Window object.
we can create a new Location object that has the current URL as follows:
Basic Structure of a URL:
- Protocol – Specifies the protocol name. It is used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
- hostname – Host name specifies the host that owns the resource. For example, www.wikitechy.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 needs to access. For example, /index.html.
- query – 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 (#).
Location object properties can access all of these URL components :
- hash – It is used to sets or returns the anchor portion of a URL.
var currenthash = window.location.hash;
- host – It is used to sets or returns the hostname and port of a URL.
var currentHost = window.location.host;
- hostname – It is used to sets or returns the hostname of a URL.
var currentHostname = window.location.hostname;
- href – It is used to sets or returns the entire URL.
var currentURL = window.location.href;
- pathname – It is used to sets or returns the path name of a URL.
var currentPathname = window.location.pathname;
- port –sets or returns the port number the server uses for a URL.
var currentPort = window.location.port;
- protocol – It is used to sets or returns the protocol of a URL.
var currentProtocol = window.location.protocol;
- search – It is used to sets or returns the query portion of a URL
var currentSearchString = window.location.search;
Get Current URL in Web browser:
To Get the URL From Firefox and Opera :
We can get current page URL in web browser using following code,
To get the path, we can use the method:
Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
For complete URL with query strings: