How to get current url in javascript

Sometimes on a button click or any other event, you need to get the current URL of the browser window. Javascript provides a simple method to determine the URL.

window object
Javascript’s window object has a property location which contains information about the current document or the window in which the script is running.
This object can be used for getting the URL and host of the current page as below.

window.location.href :           Will return the complete URL of the current page.            Will return the host and port from the URL of the current page.
window.location.hostname:   Will return only the name of host from the URL of the current page.
window.location.port:            Will return only the port from the current URL.
window.location.protocol:     Will return only the protocol(http or https) over which the current page was loaded.

Thus, assuming the URL of current displayed page in browser is, then above properties will return following values.

Property Returned Value Explanation
window.location.href Complete URL Host(or ip) and port from URL
window.location.hostname Only host(or ip) from URL
window.location.port 8080 Only port from URL
window.location.protocol http: Only protocol of URL

You can also use location directly without prefixing it with window since window object is implicitly present in javascript.
Also, note that the type of the value returned by all the above properties is a string.


Mark Your Impression

Close Menu