Get the current URL with JavaScript?

Asked : Nov 17

Viewed : 23 times

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.

javascript url 

Nov 17

3 Answers

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.

answered Jan 16


Use the window.location.href Property

You can use the JavaScript window.location.href property to get the entire URL of the current page which includes hostname, query-string, fragment identifier, etc.

The following example will display the current URL of the page at the click of the button.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Current URL in JavaScript</title>
</head>
<body>
    <script>
    function getURL() {
        alert("The URL of this page is: " + window.location.href);
    }
    </script>
     
    <button type="button" onclick="getURL();">Get Page URL</button>
</body>
</html>

answered Jan 16


How to Get Current URL in JavaScript

In JavaScript, the Location object contains the information regarding the URL of the currently loaded webpage. It belongs to window, though, we can access it directly because window is hierarchically located at the top of the scope

To get the current URL, we'll leverage the Location object and retrieve its href property:

var url = window.location.href
console.log(url)

This results in:

https://www.hrefcode.com:8080/python/article-title.html?searchterm=Example+title#2

The href the property contains the full URL to the currently loaded resource. If you'd like to retrieve certain components, rather than the entire URL, the Location the object has various properties as well.

answered Jan 16


Login and Submit Your Answer
Browse other questions tagged  javascript  url or ask your own question.