No Time to Read - Copy/Paste Solution
function getCurrentURL () {return window.location.href}// Exampleconst url = getCurrentURL()url // https://ui.dev/get-current-url-javascript/
Simple enough. If you're using JavaScript in the browser you can get the full current URL by using window.location.href
. I think it's also worth noting that window.location
has a bunch of different properties on it that may be of use to you as well.
Let's assume this is the current URL we're on
https://ui.dev/get-current-url-javascript/?comments=false
These are all the properties that window.location
gives us.
const {host, hostname, href, origin, pathname, port, protocol, search} = window.locationhost // "ui.dev"hostname // "ui"href // "https://ui.dev/get-current-url-javascript/?comments=false"origin // "https://ui.dev"pathname // "/get-current-url-javascript/""port // ""protocol // "https:"search // "?comments=false"