index.js 967 B

1234567891011121314151617181920212223
  1. window.regions = document.querySelectorAll('link[rel=region]');
  2. window.regionMap = {};
  3. window.regions.forEach(function(item) {
  4. window.regionMap[item.attributes.regionflag.value] = item.attributes.href.value;
  5. });
  6. let xhr = new XMLHttpRequest();
  7. xhr.open("GET", "https://api.ipify.org/?format=json");
  8. xhr.addEventListener("loadend", async function (e){
  9. let responseObj = JSON.parse(this.response);
  10. let ip = responseObj.ip;
  11. let regionData = await ipToRegion(ip);
  12. let country = window.location.protocol === 'https:' ? regionData.country_name : regionData.geoplugin_countryName
  13. if (window.regionMap[country]) {
  14. window.location.href = window.regionMap[country]
  15. }
  16. });
  17. xhr.send();
  18. async function ipToRegion(ip) {
  19. let url = window.location.protocol === 'https:' ? `/ipdata.php?ip=${ip}` : `http://www.geoplugin.net/json.gp?ip=${ip}`
  20. const response = await fetch(url);
  21. const data = await response.json();
  22. return data;
  23. }