Hugh Harlequin 1 year ago
commit
87767abc5e
2 changed files with 40 additions and 0 deletions
  1. 19 0
      demo.html
  2. 21 0
      index.js

+ 19 - 0
demo.html

@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <title>My Website</title>
+    <link rel="stylesheet" href="./style.css">
+    <link rel="icon" href="./favicon.ico" type="image/x-icon">
+    <link rel="region" href="https://www.google.com" regionflag="Taiwan">
+    <script src="index.js"></script>
+
+  </head>
+  <body>
+    <main>
+        <h1>Welcome to My Website</h1>  
+    </main>
+  </body>
+</html>

+ 21 - 0
index.js

@@ -0,0 +1,21 @@
+window.regions = document.querySelectorAll('link[rel=region]');
+window.regionMap = {};
+window.regions.forEach(function(item) { 
+    window.regionMap[item.attributes.regionflag.value] = item.attributes.href.value;
+});
+let xhr = new XMLHttpRequest();
+xhr.open("GET", "https://api.ipify.org/?format=json");
+xhr.addEventListener("loadend", async function (e){
+    let responseObj = JSON.parse(this.response);
+    let ip = responseObj.ip;
+    let regionData = await ipToRegion(ip);
+    if (window.regionMap[regionData.geoplugin_countryName]) {
+        window.location.href = window.regionMap[regionData.geoplugin_countryName]
+    }
+});
+xhr.send();
+async function ipToRegion(ip) {
+    const response = await fetch(`http://www.geoplugin.net/json.gp?ip=${ip}`);
+    const data = await response.json();
+    return data;
+}