Redirect Java Script or HTML

Asked

Viewed 48 times

-4

I would like to be doing the same redirection based on user’s location. has this possibility?

ex: if he is in Brazil remains on the site. if he is from another country is automatically redirected to another site.

Thank you

2 answers

1

There is this possibility Bernardo :). You can use some service that already provided you this information for example:

For these 4, you need to pay a fee for consultations depending on the plan. A free alternative is the ip-api. To test your location, go to the url below in your browser:

http://ip-api.com/json

On your website, you will need this code snippet well before the tag body closes:

 $(document).ready(function(){
     $.get({
         url:'http://ip-api.com/json', 
         timeout: 5000
     }).then(
         //Funcao de sucesso
         function success(response) {
            if(!response.country === "Brazil") {
                //Caso sim, redireciona para outra url
                window.location.href = "https://www.nytimes.com/";
             }
         }, 
         //Funcao de erro
         function fail(data, status) {
            //Continua no site em portugues
         }
      );
 });

It will be necessary to have imported the jQuery. Remembering that as it is a free service, you can suffer intermittence/ slowness for the calls. Details: country names are returned in English.

  • Good night, all right? Unfortunately that code isn’t working. I registered in the " ipgeolocation " and I took the activation key to implement it, but it still doesn’t work. :/

0

Bernardo, the only necessary modifications to this code, is the URL you should use and the parameter that returns the country name. The url must follow the following pattern: https://api.ipgeolocation.io/ipgeo?apiKey=API_KEY, where API_KEY should be replaced by the value found on your tool’s Dashboard in the section "Your API Key". The field that returns the country name changes to country_name. Thus, the above code for the ipgeolocation stays:

<script type="text/javascript">
    $(document).ready(function(){
        $.get({
            url:'https://api.ipgeolocation.io/ipgeo?apiKey=1234567890', 
            timeout: 5000
        }).then(
            //Funcao de sucesso
            function success(response) {
                if(!response.country_name === "Brazil") {
                    //Caso sim, redireciona para outra url
                    window.location.href = "https://www.nytimes.com/";
                }
            }, 
            //Funcao de erro
            function fail(data, status) {
                //Continua no site em portugues
            }
        );
    });
</script>`

Browser other questions tagged

You are not signed in. Login or sign up in order to post.