Changing URL based on City/Region

mail@pastecode.io avatar
unknown
plain_text
6 months ago
1.7 kB
2
Indexable
Never
<script>
// Easily modifiable variables
const apiKey = 'ce426858857a4778899e4ac280be4c17'; // Replace with your API key
const originalUrl = 'http://americanlifenow.com/click”';
const newUrl = 'https://www.moneytalksnews.com/painless-ways-for-seniors-to-save-money/';
const targetCities = [
    "Atlanta, Georgia",
    "Boston, Massachusetts",
    "Chicago, Illinois",
    "Dallas, Texas",
    "Denver, Colorado",
    "Kansas City, Missouri",
    "New York, New York",
    "Philadelphia, Pennsylvania",
    "San Francisco, California",
    "Seattle, Washington"
];
const targetState = "Florida"; // Targeting the entire state

async function getUserLocation() {
    try {
        const response = await fetch(`https://ipgeolocation.abstractapi.com/v1/?api_key=${apiKey}`);
        const data = await response.json();
        return { city: data.city, state: data.region, isVpn: data.security.is_vpn }; // Return city, state, and VPN status
    } catch (error) {
        console.error('Error fetching user location:', error);
        return null;
    }
}

async function updateLinksBasedOnLocation() {
    const userLocation = await getUserLocation();
    if (userLocation && !userLocation.isVpn) { // Check if location is available and not a VPN
        const cityStateCombination = `${userLocation.city}, ${userLocation.state}`;

        if (targetCities.includes(cityStateCombination) || userLocation.state === targetState) {
            document.querySelectorAll(`a[href="${originalUrl}"]`).forEach(link => {
                link.href = newUrl;
            });
        }
    }
}

document.addEventListener('DOMContentLoaded', updateLinksBasedOnLocation);
</script>
Leave a Comment