Question

Get the current URL with JavaScript?

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.

 3780  3836311  3780
1 Jan 1970

Solution

 4523

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.

2009-06-23
VolkerK

Solution

 897

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:

let 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 - i.e. window.location.href
  • 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
2013-12-23
Nikhil Agrawal

Solution

 342

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.

2009-06-23
Christoph

Solution

 314

Gets the current page URL:

window.location.href
2009-06-23
Zanoni

Solution

 118

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

2017-10-07
Alireza

Solution

 54

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

2017-06-09
Tmh

Solution

 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

2015-09-10
Sangeet Shah

Solution

 32

Use: window.location.href.

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

2014-04-25
Dorian

Solution

 29

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

2022-08-17
Siddhartha Mukherjee

Solution

 25
  • Use window.location.href to get the complete URL.
  • Use window.location.pathname to get URL leaving the host.
2015-03-26
kishore

Solution

 22
// 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
2021-12-18
Weilory

Solution

 21

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');
2016-10-08
Bhaskar Bhatt

Solution

 20

For complete URL with query strings:

document.location.toString()

For host URL:

window.location
2014-09-05
Syed Nasir Abbas

Solution

 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"
2017-11-03
Hitesh Sahu

Solution

 11
var currentPageUrlIs = "";
if (typeof this.href != "undefined") {
       currentPageUrlIs = this.href.toString().toLowerCase(); 
}else{ 
       currentPageUrlIs = document.location.toString().toLowerCase();
}
2013-12-19
Rohan Patil

Solution

 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.)

2019-12-27
Apollo Data

Solution

 8

Simply use this:

document.URL

or this:

window.location.href

2023-03-25
Blackjack

Solution

 7

You have multiple ways to do this.

1:

location.href;

2:

document.URL;

3:

document.documentURI;
2021-01-01
Programmer

Solution

 6
location.origin+location.pathname+location.search+location.hash;

and

location.href

does the same.

2017-04-06
Sos.

Solution

 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.

2015-09-29
Josip Ivic

Solution

 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.

2016-04-12
Maleen Abewardana

Solution

 4

Short

location+''

let url = location+'';

console.log(url);

2020-01-01
Kamil Kiełczewski

Solution

 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('/'));
2017-03-14
Khaled Harby

Solution

 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.

2018-06-30
curiosity

Solution

 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 );
});
2018-10-09
Ashish Kamble