JavaScript and jQuery script to get current URL

By | August 8, 2020
In this article, I am going to explain two ways to get current URL using JavaScript and jQuery code snippet.

 
1) Get current URL using JavaScript: In below script, I have created a function alertURL() that will fetch the current URL using window.location.href method of the JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Get Current Page URLtitle>
head>
<body>
<input type="button" id="alerturl" value="Print Current URL" onclick="alertURL();">

<script type="text/javascript">
function alertURL(){
 var cur_loc = window.location.href;
 alert(cur_loc);
}
script>
body>
html>
 
Output:

 

 

2) Get Current URL using jQuery: 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Get Current Page URLtitle>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">script>
head>
<body>
<input type="button" id="alerturl" value="Print Current URL">
<span id="print_msg">span>
<script type="text/javascript">
$(document).ready(function(){
 $('#alerturl').click(function(){
 var current_page = $(location).attr('href');
 $('#print_msg').html('Your current URL is: '+current_page);
 });
});
script>
body>
html>

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *