JavaScript provides multiple methods to get the current URL displayed in the web browser address bar. You can use the Location object property of the Window object to get these details. Below is the list of a few properties of the location objects.
Here is the list of options available to get URLs and other details using JavaScript. The first example will get the current URL in a web browser. Other examples are also available for your reference.
#1 – href
This will return the entire URL displayed in the address bar.
1 | var currentURL = window.location.href; |
#2 – host
This will return the hostname and port of the URL in the address bar.
1 | var currentHost = window.location.host; |
#3 – hostname
This will return only the hostname of the URL in the address bar.
1 | var currentHostname = window.location.hostname; |
#4 – port
This will return only the port detail of the URL in the address bar.
1 | var currentPort = window.location.port; |
#5 – protocol
This will return the protocol of the URL in the address bar. Like the URL is using HTTP (without SSL) or HTTPS (with SSL).
1 | var currentProtocol = window.location.protocol; |
#6 – pathname
This will return the pathname (value after the domain name) of the URL in the address bar.
1 | var currentPathname = window.location.pathname; |
#7 – hash
This will return the anchor portion of the URL including the hash sign (#).
1 | var currenthash = window.location.hash; |
#8 – search
This will return the query portion of the URL-like portion started with the question mark (?).
1 | var currentSearchString = window.location.search; |
6 Comments
I’ve tested this with an iframe embedded in a page in freshdesk.
It returns the URL of the iframe and not what’s in the address bar of the browser.
thank you this post is wonderful 🙂
Hmmm…. I’ve tested this with an iframe embedded in a page and ran the query within the iframe page.
It returns the URL of the iframe and not what’s in the address bar of the browser.
Might need tweaking using parent.location – but I have no idea, sorry.
Sorry, meant top.location, not parent.location
Thank you. This is extremely useful. BTW, in #4 I think you meant – port. But the code is right and that’s what matters!
We provide solution regarding Google chrome. If your Google chrome web browser is not responding then visit us. We provide full assistance regarding it.