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.

PropertyReturned ValueExplanation
window.location.hrefhttp://127.0.0.1:8080/javascriptdemoComplete URL
window.location.host127.0.0.1:8080Host(or ip) and port from URL
window.location.hostname127.0.0.1Only host(or ip) from URL
window.location.port8080Only port from URL
window.location.protocolhttp: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.

0

Mark Your Impression

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.