3694

All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a variable to do with as I please.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

26 Answers26

4438

Use:

window.location.href

As noted in the comments, the line below works, but it is bugged for Firefox.

document.URL

See URL of type DOMString, readonly.

GalAbra
  • 5,048
  • 4
  • 23
  • 42
VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • 161
    In Firefox 12 the `document.URL` property doesn't update after a `window.location` to an anchor (#), while `window.location.href` does. I didn't test any other versions of Firefox. No issues using `document.URL` were found in Chrome 20 and IE9. – Telmo Marques Jul 07 '12 at 16:26
  • 103
    also you can get host and clear location: `window.location.host` and `window.location.href.toString().split(window.location.host)[1]` – Ali U Nov 26 '12 at 11:59
  • 11
    and what's `document.baseURI` about then. Basically there are 3 ways to get url `document.baseURI`, `document.URL`, & `location`. – Muhammad Umer Aug 29 '13 at 12:06
  • 26
    -1: If you have a frame, image, or form with `name="URL"` then this property will be shadowed on the `document` object and your code will break. In that case, `document.URL` will refer to the DOM node instead. Better to use properties of the global object as in `window.location.href`. – Roy Tinker Dec 05 '13 at 00:02
  • This is kind of confusing for someone looking for the rigth info (I just mean there must be an edit to show `window.location.href` instead of `document.URL` as the answer) – Gerardo Charles Rojas Vega Nov 29 '14 at 02:16
  • 4
    @aliyouhannaei you could also do `window.location.pathname` to get just the path – wranvaud Oct 29 '19 at 14:03
  • 1
    `window.location.pathname` //yields: "/js" (where url is "https://stacksnippets.net/js") – Md. A. Apu Jun 29 '20 at 06:48
  • 1
    @AliU toString() should not be necessary as the former is a string. – Timo Mar 12 '21 at 19:36
882

URL Info Access

JavaScript provides you with many methods to retrieve and change the current URL, which is displayed in the browser's address bar. All these methods use the Location object, which is a property of the Window object. You can read the current Location object by reading window.location:

var currentLocation = window.location;

Basic URL Structure

<protocol>//<hostname>:<port>/<pathname><search><hash>
  • 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, /index.html.

  • 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 (#).

With these 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
  • origin - the window.location.protocol + '//' + window.location.host
TylerH
  • 20,799
  • 66
  • 75
  • 101
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
  • 14
    They are not "methods" of `window.location`, but properties, and [here we have an example](http://stackoverflow.com/a/406208): `var stringPathName = window.location.pathname`. – Peter Krauss Jul 22 '14 at 22:18
  • 1
    @FabioC. You can remove it by `substring`. However, it may be useful when you want to use to redirect `document.location = "/page.html";` will redirect to root page `page.html` – FindOut_Quran Dec 23 '16 at 05:11
  • 1
    Keep in mind ie9 `pathname` does not have a leading slash, so it could be `index.html`. – AJcodez Jun 05 '17 at 14:55
  • 6
    This answers more than just the question stated. In fact, I searched probably around a month ago for a good way to get one or more specific parts out of the URL string (I think it was probably the current page I was trying to get), and even though other questions were more on-target, their answers were not as useful and straightforward for that purpose as this one. – Panzercrisis Jan 07 '19 at 07:10
  • 2
    One quick suggestion though: In the basic URL structure described above, there's a spot for `search`, but in the list of descriptions below, it's called a `query`. Maybe either they can be reconciled, or further explanation can be added. – Panzercrisis Jan 07 '19 at 07:11
  • 2
    It's called 'search' not 'query' – Apollo Data Dec 27 '19 at 17:01
341

Use window.location for read and write access to the location object associated with the current frame. If you just want to get the address as a read-only string, you may use document.URL, which should contain the same value as window.location.href.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Christoph
  • 164,997
  • 36
  • 182
  • 240
  • 19
    see also http://stackoverflow.com/questions/2430936/whats-the-difference-between-window-location-and-document-location-in-javascript/2431375#2431375 – Christoph Mar 12 '10 at 09:06
309

Gets the current page URL:

window.location.href
Zanoni
  • 30,028
  • 13
  • 53
  • 73
  • 5
    Note that that’s the window’s location not the document’s. – Gumbo Jun 23 '09 at 19:32
  • 19
    It's the same thing. Full current URL refers to the document path (external address). – Zanoni Jun 23 '09 at 19:34
  • 3
    Is it standardized like document.url? (I mean something like a w3c document) – chendral Jun 23 '09 at 19:47
  • 2
    `document` is the root of the document tree defined by the spec. `window` is generally equivalent but it might not be in some weird circumstances. – broinjc Sep 19 '14 at 16:19
  • "`window` is generally equivalent" Nope. Never been the case. A [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) is very different from a [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Document) – Heretic Monkey Mar 23 '23 at 21:35
107

OK, getting the full URL of the current page is easy using pure JavaScript. For example, try this code on this page:

window.location.href;
// use it in the console of this page will return
// http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser"

The window.location.href property returns the URL of the current page.

document.getElementById("root").innerHTML = "The full URL of this page is:<br>" + window.location.href;
<!DOCTYPE html>
<html>

<body>
  <h2>JavaScript</h2>
  <h3>The window.location.href</h3>
  <p id="root"></p>
</body>

</html>

Just not bad to mention these as well:

  • if you need a relative path, simply use window.location.pathname;

  • if you'd like to get the host name, you can use window.location.hostname;

  • and if you need to get the protocol separately, use window.location.protocol

  • also, if your page has hash tag, you can get it like: window.location.hash.

So window.location.href handles all in once... basically:

window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
    //true

Also using 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

Get the current URL with JavaScript

TylerH
  • 20,799
  • 66
  • 75
  • 101
Alireza
  • 100,211
  • 27
  • 269
  • 172
  • 1
    The only thing missing is: `window.location.port `. When possibly dealing with a port: ```window.location.protocol + '//' + window.location.hostname + (window.location.port ? ":" + window.location.port : '') + window.location.pathname + window.location.hash === window.location.href``` – Kerwin Sneijders Feb 04 '23 at 11:33
  • Your answer is missing `window.location.search` as `window.location.href` also provide query params. – Aivus Aug 04 '23 at 13:39
48

Open Developer Tools, type in the following in the console and press Enter.

window.location

Ex: Below is the screenshot of the result on the current page.

enter image description here

TylerH
  • 20,799
  • 66
  • 75
  • 101
Tmh
  • 1,321
  • 14
  • 27
47

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
Elena
  • 364
  • 2
  • 9
Sangeet Shah
  • 3,079
  • 2
  • 22
  • 25
32

Use: window.location.href.

As noted above, document.URL doesn't update when updating window.location. See MDN.

Dorian
  • 22,759
  • 8
  • 120
  • 116
25
  • Use window.location.href to get the complete URL.
  • Use window.location.pathname to get URL leaving the host.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kishore
  • 1,658
  • 7
  • 24
  • 33
25

To get the path, you can use:

http://www.example.com:8082/index.php#tab2?foo=789

Property                    Result
------------------------------------------
window.location.host        www.example.com:8082
window.location.hostname    www.example.com
window.location.port        8082
window.location.protocol    http:
window.location.pathname    index.php
window.location.href        http://www.example.com:8082/index.php#tab2
window.location.hash        #tab2
window.location.search      ?foo=789
window.location.origin      https://example.com

enter image description here

Siddhartha Mukherjee
  • 2,703
  • 2
  • 24
  • 29
20

For complete URL with query strings:

document.location.toString()

For host URL:

window.location
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Syed Nasir Abbas
  • 1,722
  • 17
  • 11
20

You can get the current URL location with a hash tag by using:

JavaScript:

 // Using href
 var URL = window.location.href;

 // Using path
 var URL = window.location.pathname;

jQuery:

$(location).attr('href');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bhaskar Bhatt
  • 1,399
  • 13
  • 19
  • Don't use `URL` as your variable name; there is already a constructor on window.URL. See here: https://developer.mozilla.org/en-US/docs/Web/API/URL/URL – frontend_friend May 11 '22 at 13:19
18

// http://127.0.0.1:8000/projects/page/2?name=jake&age=34
let url = new URL(window.location.href);
/*
hash: ""

host: "127.0.0.1:8000"

hostname: "127.0.0.1"

href: "http://127.0.0.1:8000/projects/page/2?username=jake&age=34"

origin: "http://127.0.0.1:8000"

password: ""

pathname: "/projects/page/2"

port: "8000"

protocol: "http:"

search: "?name=jake&age=34"

username: ""
*/

url.searchParams.get('name')
// jake

url.searchParams.get('age')
// 34

url.searchParams.get('gender')
// null
Weilory
  • 2,621
  • 19
  • 35
14

window.location:

 Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
 ancestorOrigins: DOMStringList,
 origin: "https://stackoverflow.com",
 replace: ƒ, assign: ƒ, …}

document.location:

  Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript", 
ancestorOrigins: DOMStringList,
 origin: "https://stackoverflow.com",
 replace: ƒ, assign: ƒ
, …}

window.location.pathname:

"/questions/1034621/get-the-current-url-with-javascript"

window.location.href:

"https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"

location.hostname:

"stackoverflow.com"
TylerH
  • 20,799
  • 66
  • 75
  • 101
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
11
var currentPageUrlIs = "";
if (typeof this.href != "undefined") {
       currentPageUrlIs = this.href.toString().toLowerCase(); 
}else{ 
       currentPageUrlIs = document.location.toString().toLowerCase();
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Rohan Patil
  • 1,865
  • 1
  • 23
  • 36
10

Nikhil Agrawal's answer is great, just adding a little example here you can do in the console to see the different components in action:

enter image description here

If you want the base URL without path or query parameter (for example to do AJAX requests against to work on both development/staging AND production servers), window.location.origin is best as it keeps the protocol as well as optional port (in Django development, you sometimes have a non-standard port which breaks it if you just use hostname etc.)

Apollo Data
  • 1,267
  • 11
  • 20
9

For those who want an actual URL object, potentially for a utility which takes URLs as an argument:

const url = new URL(window.location.href)

https://developer.mozilla.org/en-US/docs/Web/API/URL

Seph Reed
  • 8,797
  • 11
  • 60
  • 125
  • The other great thing about this method is that you can use it as a URL builder- add or remove params, change the path, etc. and then use the .toString() method to always get a perfectly valid, nicely formatted URL string! – frontend_friend May 11 '22 at 13:22
6

You have multiple ways to do this.

1:

location.href;

2:

document.URL;

3:

document.documentURI;
Programmer
  • 365
  • 2
  • 9
5

The way to get the current location object is window.location.

Compare this to document.location, which originally only returned the current URL as a string. Probably to avoid confusion, document.location was replaced with document.URL.

And, all modern browsers map document.location to window.location.

In reality, for cross-browser safety, you should use window.location rather than document.location.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Josip Ivic
  • 3,639
  • 9
  • 39
  • 57
5

In jstl we can access the current URL path using pageContext.request.contextPath. If you want to do an Ajax call, use the following URL.

url = "${pageContext.request.contextPath}" + "/controller/path"

Example: For the page http://stackoverflow.com/posts/36577223 this will give http://stackoverflow.com/controller/path.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Maleen Abewardana
  • 13,600
  • 4
  • 36
  • 39
5
location.origin+location.pathname+location.search+location.hash;

and

location.href

does the same.

Sos.
  • 914
  • 10
  • 14
5

Simply use this:

document.URL

or this:

window.location.href

Blackjack
  • 1,322
  • 1
  • 16
  • 21
3

You can get the full link of the current page through location.href and to get the link of the current controller, use:

location.href.substring(0, location.href.lastIndexOf('/'));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
3

Short

location+''

let url = location+'';

console.log(url);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
1

if you are referring to a specific link that has an id this code can help you.

$(".disapprove").click(function(){
    var id = $(this).attr("id");

    $.ajax({
        url: "<?php echo base_url('index.php/sample/page/"+id+"')?>",
        type: "post",
        success:function()
        {
            alert("The Request has been Disapproved");
            window.location.replace("http://localhost/sample/page/"+id+"");
        }
    });
});

I am using ajax here to submit an id and redirect the page using window.location.replace. just add an attribute id="" as stated.

JGallardo
  • 11,074
  • 10
  • 82
  • 96
curiosity
  • 834
  • 8
  • 20
0

Firstly check for page is loaded completely in

browser,window.location.toString();

window.location.href

then call a function which takes url, URL variable and prints on console,

$(window).load(function(){
   var url = window.location.href.toString();
   var URL = document.URL;
   var wayThreeUsingJQuery = $(location).attr('href');
   console.log(url);
   console.log(URL);
   console.log(wayThreeUsingJQuery );
});
Ashish Kamble
  • 2,555
  • 3
  • 21
  • 29