How to retrieve the full URL from browser address bar using javascript

Pranay
Sep 04, 2014  ·  1428 views

To get the complete URL in the current browser window, use ‘window.location.href’ in javascript. There are many other properties (listed below) which return details on browser URL.

window.location.href - Returns the complete URL of the current page

window.location.hostname - returns the domain name of the web host

window.location.host - Returns the domain name along with the port number if any

window.location.protocal - Returns the web protocol used i.e., http: or https:

window.location.pathname - Returns the relative path of the current page.

Window.location.hash - Returns the hash string in the URL. URL string followed by ‘#’ is called as hash string.

Window.location.assign() - A function to change the current URL or page.

Example:

Sample URL: http://localhost:45697/articles/test#myStr

If we consider the above sample URL, below are the results we get on using these properties.

window.location.hash(property): myStr (result)

window.location.href: http://localhost:49247/posts/test

window.location.host: localhost:49247

window.location.hostname: localhost

window.location.pathname: /posts/test

window.location.protocal: http:

window.location.assign(url): Redirects the current page to the new ‘url’

AUTHOR

Pranay

A Software Engineer by profession, a part time blogger and an enthusiast programmer. You can find more about me here.


Post a comment




Thank you! You are now subscribed.

Sign up for our newsletter

Subscribe to receive updates on our latest posts.

Thank you! You are now subscribed.