Search code examples
javascriptjquerysquarespace

How to detect visitor country using simple Javascript


This code is not working on squarespace, can someone identify whats wrong with this code. However, its working on jsfiddle.

<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>


<script>
 jQuery(document).ready(function($) {
    jQuery.getScript('http://www.geoplugin.net/javascript.gp', function() 
    {
        var country = geoplugin_countryName();
        alert(country);
        var code = geoplugin_countryCode();
        alert(code);
        console.log("Your location is: " + country + ", " + zone + ", " + district);
    });
});</script>

Solution

  • I have added the code for region and city which was missing, try this it works now,

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
    <script>
    jQuery(document).ready(function($) {
        jQuery.getScript('http://www.geoplugin.net/javascript.gp', function() 
        {
            const country = geoplugin_countryName();
            const countryCode = geoplugin_countryCode();
            const city = geoplugin_city();
            const region = geoplugin_region();
            console.log(`Your location is: ${city}, ${region}, ${country}, ${countryCode}`);
            alert(`Your location is: ${city}, ${region}, ${country}, ${countryCode}`)
        });
    });

    Update:-

    As the above plugin was hosted over HTTP and was giving error, this is the alternate solution to it,

    fetch('https://extreme-ip-lookup.com/json/')
      .then(res => res.json())
      .then(res => {
        console.log(res);
        document.getElementById('target').innerHTML = `Your location is: ${res.city}, ${res.region}, ${res.country}`;
      })
      .catch((data, status) => {
        console.log('Request failed');
      })