Created
April 29, 2024 05:14
-
-
Save abdullahdevrel/28edfa57ea4e284bcff55219606f2538 to your computer and use it in GitHub Desktop.
Redirect traffic based on IP Geolocation with IPinfo.io
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Define a function named getJSON that takes a URL and a callback function as parameters | |
| var getJSON = function(url, callback) { | |
| // Create a new XMLHttpRequest object | |
| var xhr = new XMLHttpRequest(); | |
| // Open a GET request to the specified URL asynchronously | |
| xhr.open('GET', url, true); | |
| // Specify the expected response type as JSON | |
| xhr.responseType = 'json'; | |
| // Define an event handler for when the request completes | |
| xhr.onload = function() { | |
| // Retrieve the HTTP status code from the response | |
| var status = xhr.status; | |
| // If the status code is 200 (OK), call the callback function with null as the error and the response data | |
| if (status == 200) { | |
| callback(null, xhr.response); | |
| } | |
| // If the status code is not 200, call the callback function with the status code as the error | |
| else { | |
| callback(status); | |
| } | |
| }; | |
| // Send the request | |
| xhr.send(); | |
| }; | |
| // Call the getJSON function with a URL and a callback function | |
| getJSON('http://ipinfo.io/json', function(err, data) { | |
| // If an error occurred during the request, log the error to the console | |
| if (err != null) { | |
| console.error(err); | |
| } | |
| // If no error occurred | |
| else { | |
| // If the country retrieved from the data is not "US", redirect to a URL for non-US visitors | |
| if (data.country != "US") { | |
| window.location.replace("http://example.com/global"); | |
| } | |
| // If the country is "US", redirect to a URL for US visitors | |
| else { | |
| window.location.replace("http://example.com/us"); | |
| } | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment