js根据地区判断进行跳转页面
<script>
// 获取访问者的 IP 地址
function getVisitorIP() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://ipinfo.io/json', true);
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
const responseData = JSON.parse(xhr.responseText);
const ip = responseData.ip;
resolve(ip);
} else {
reject(new Error('Failed to fetch IP address.'));
}
};
xhr.onerror = function () {
reject(new Error('Network error while fetching IP address.'));
};
xhr.send();
});
}
// 根据 IP 地址获取城市信息
function getCityFromIP(ip) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', `https://ipapi.co/${ip}/json/`, true);
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
const responseData = JSON.parse(xhr.responseText);
const city = responseData.city;
resolve(city);
} else {
reject(new Error('Failed to fetch city information.'));
}
};
xhr.onerror = function () {
reject(new Error('Network error while fetching city information.'));
};
xhr.send();
});
}
// 判断是否是北上广深长沙
function isTargetCity(city) {
const targetCities = ['北京', '上海', '广州', '深圳'];
return targetCities.includes(city);
}
// 跳转逻辑
function redirectToBaidu() {
window.location.href = 'https://4399.com/';
}
// 主逻辑:获取 IP 地址,然后根据 IP 地址获取城市信息,最后判断是否是目标城市
function checkCityAndRedirect() {
getVisitorIP()
.then((ip) => getCityFromIP(ip))
.then((city) => {
console.log('Visitor city:', city);
if (isTargetCity(city)) {
redirectToBaidu();
} else {
console.log('Not in target cities.');
}
})
.catch((error) => {
console.error('Error:', error.message);
});
}
// 在页面加载完成后执行逻辑
window.onload = function () {
checkCityAndRedirect();
};
</script>
千行代码,Bug何处藏。 纵使上线又怎样,朝令改,夕断肠。

浙公网安备 33010602011771号