The IP Address Fetcher is a simple yet powerful tool that retrieves the IP address of the visitors accessing your website. By integrating this source code into your website, you can gather valuable information about your users, such as their location and network details.
window.addEventListener('DOMContentLoaded', function() {
// Get the user's public IP address
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
var ipAddress = data.ip;
// Get the user's location using the ipapi service
fetch('https://ipapi.co/' + ipAddress + '/json/')
.then(response => response.json())
.then(data => {
var city = data.city;
var region = data.region;
var country = data.country_name;
// Get the current date and time
var currentDate = new Date();
// Format the date and time as desired
var formattedDate = currentDate.toLocaleDateString();
var formattedTime = currentDate.toLocaleTimeString();
// Create the greeting message with location and time
var greeting = "Hello! You are located in " + city + ", " + region + ", " + country +
". The current date is: " + formattedDate +
" and the time is: " + formattedTime + ".";
// Display the greeting message in the location alert
var locationAlert = document.querySelector('.location-alert');
locationAlert.querySelector('#location').textContent = greeting;
})
.catch(error => {
console.log('Error:', error);
var locationAlert = document.querySelector('.location-alert');
locationAlert.querySelector('#location').textContent = "Failed to fetch location information.";
});
})
.catch(error => {
console.log('Error:', error);
var locationAlert = document.querySelector('.location-alert');
locationAlert.querySelector('#location').textContent = "Failed to fetch IP address.";
});
});