In JavaScript, we can get the current URL of the page using the window.location object. The window.location object contains information about the current URL of the page.
We can get URL from another method also, which is document.URL. Another method is document.documentURI which returns the location of the document as a string.
Using window.location
The window.location object can be used to get the current URL. The window.location.href property 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 use window.location.href to get the current URL. In below example you can try using window.location or location in place of window.location.href.
<html><body><p id="demo"></p><script>let currentURL = window.location.href; document.getElementById("demo").innerHTML = currentURL;</script></body></html>
Output
We execute the code online. When you run the above code, You will able to see console message with the current URL.
Using document.URL
We could also use document.documentURI and document.URL properties. The document.URL returns 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.
<html><body><p id="demo"></p><script>let currentURL = document.URL; document.getElementById("demo").innerHTML = currentURL;</script></body></html>
Output
When you execute the above code, In console the current URL will be displayed.
Using document.documentURI
The document.documentURI returns 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.
<html><body><p id="demo"></p><script>let currentURL = document.documentURI; document.getElementById("demo").innerHTML = currentURL;</script></body></html>
Output
When you execute the above code, In console you will be able to see the current URL of the document.
Leave a Reply