Site icon codippa

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.
window.location.host:            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 http://127.0.0.1:8080/javascriptdemo, then above properties will return following values.

Property Returned Value Explanation
window.location.href http://127.0.0.1:8080/javascriptdemo Complete URL
window.location.host 127.0.0.1:8080 Host(or ip) and port from URL
window.location.hostname 127.0.0.1 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.

Exit mobile version