Two ways to Get URL of current page using JavasScript

Share:

1. document.URL
2. window.location.href

window.location is an object and has many properties.
Some common properties are : href, hostname, pathname, protocol and port.

Example: Suppose current page URL is https://www.codebrary.com/search/label/JavaScript

window.location.href returns the href (URL) of the current page
result: https://www.codebrary.com/search/label/JavaScript

window.location.hostname returns the domain name of the web host
result: www.codebrary.com

window.location.pathname returns the path and filename of the current page
result: /search/label/JavaScript

window.location.protocol returns the web protocol used (http: or https:)
result: https:

window.location.port returns the number of the internet host port (of the current page).
result: 443

NOTE: 
1. Most browsers will not display the default port numbers which is 80 for http and 443 for https

2. The window.location object can be written without the window prefix.
To avoid bugs best practise is to use with windows prefix because the nature of Javascript's scoping allows you to override variables. This means that you could have set var location somewhere in a containing scope.

Hi! I am Sartaj Husain. I am a Professional Software Developer, live in Delhi. I write blogs in my free time. I love to learn and share the knowledge with others because it is no good to try to stop knowledge from going forward. So free posts and tutorials. more..

No comments