To get the current URL in JavaScript, we can use use window.location.href method. It returns the current opened URL.
Example program :
Create one index.html file and put the below code in it :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sample</title>
</head>
<body>
<script>
function alertCurrentURL() {
alert(`Current URL: ${window.location.href}`);
}
</script>
</body>
<button onClick="alertCurrentURL()">Show current URL</button>
</html>
The JavaScript code is written inside the tags. We have defined a function in it. This function shows the current URL as alert.
The button is a HTML component. On click, it calls the alertCurrentURL function that shows the URL in an alert. Open the index.html file in a web browser and you can see your file location in the alert.