CodesCompiler
🔍
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact 🚀 Get Started Free

JavaScript - Get Current URL

JavaScript - Get the Current URL

In JavaScript, we can get the current URL of the page using thewindow.locationobject. Thewindow.locationobject contains information about the current URL of the page.

We can get URL from another method also, which isdocument.URL. Another method isdocument.documentURIwhich returns the location of the document as a string.

Using window.location

Thewindow.locationobject can be used to get the current URL. Thewindow.location.hrefproperty returns the href (URL) of the current page. We can also use window.location or location in place of window.location.href.

Example

In this example we will usewindow.location.hrefto get the current URL. In below example you can try using window.location or location in place of window.location.href.

Preview

Output

We execute the code online. When you run the above code, You will able to see console message with the current URL.

JAVASCRIPT CODE
https://www.codescompiler.com/javascript/javascript_get_current-url.php

Usingdocument.URL

We could also use document.documentURI and document.URL properties. Thedocument.URLreturns the URL of the document as a string.

Example

In this example, we will use the document.URL to get the current URL of the document.

Preview

Output

When you execute the above code, In console the current URL will be displayed.

JAVASCRIPT CODE
https://www.codescompiler.com/javascript/javascript_get_current_url.php

Usingdocument.documentURI

Thedocument.documentURIreturns the location of the document as a string.

Example

In this example, we will use the document.documentURI to get the current URL of the document.

Preview

Output

When you execute the above code, In console you will be able to see the current URL of the document.

JAVASCRIPT CODE
https://www.codescompiler.com/javascript/javascript_get_current_url.php