As noted in the comments, the line below works, but it is bugged for Firefox.
Read more... Read less...
URL Info Access
Location object, which is a property of the
Window object. You can create a new
Location object that has the current URL as follows:
var currentLocation = window.location;
Basic URL Structure
protocol: Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
hostname: Host name specifies the host that owns the resource. For example,
www.stackoverflow.com. A server provides services using the name of the host.
port: A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
pathname: The path gives info about the specific resource within the host that the Web client wants to access. For example,
search: A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
hash: The anchor portion of a URL, includes the hash sign (#).
Location object properties you can access all of these URL components and what they can set or return:
- href - the entire URL
- protocol - the protocol of the URL
- host - the hostname and port of the URL
- hostname - the hostname of the URL
- port - the port number the server uses for the URL
- pathname - the path name of the URL
- search - the query portion of the URL
- hash - the anchor portion of the URL
I hope you got your answer..
Gets the current page URL:
window.location.href; // use it in the console of this page will return // http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser"
window.location.hrefproperty returns the URL of the current page.
document.getElementById("root").innerHTML = "The full URL of this page is:<br>" + window.location.href;
Just not bad to mention these as well:
if you need a relative path, simply use
if you'd like to get the host name, you can use
and if you need to get the protocol separately, use
- also, if your page has
hashtag, you can get it like:
- also, if your page has
window.location.href handles all in once... basically:
window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href; //true
window is not needed if already in window scope...
So, in that case, you can use:
location.protocol location.hostname location.pathname location.hash location.href
To get the path, you can use:
console.log('document.location', document.location.href); console.log('location.pathname', window.location.pathname); // Returns path only console.log('location.href', window.location.href); // Returns full URL