写一个检测地区的js代码

查看 35|回复 5
作者:钱途迷茫   
优先使用太平洋IP接口http://whois.pconline.com.cn/ipJson.jsp
要求如下
用于html页面里使用
安徽地区跳转到https://baidu.com
江苏地区跳转到https://sohu.com
其他地区跳转到https://qq.com

地区, 跳转到

congcongzhidao   

[JavaScript] 纯文本查看 复制代码// 地区检测和跳转函数
function detectLocationAndRedirect() {
    // 创建JSONP请求
    const script = document.createElement('script');
    const callbackName = 'ipCallback_' + Date.now();
   
    // 定义回调函数
    window[callbackName] = function(data) {
        try {
            let province = '';
            
            // 获取省份信息
            if (data && data.pro) {
                province = data.pro;
            } else if (data && data.addr) {
                // 备用解析方式,从addr字段提取省份
                const addrParts = data.addr.split(' ');
                if (addrParts.length > 0) {
                    province = addrParts[0];
                }
            }
            
            console.log('检测到的省份:', province);
            
            // 根据省份进行跳转
            if (province.includes('安徽')) {
                window.location.href = 'https://baidu.com';
            } else if (province.includes('江苏')) {
                window.location.href = 'https://sohu.com';
            } else {
                window.location.href = 'https://qq.com';
            }
        } catch (error) {
            console.error('处理地区信息时出错:', error);
            // 出错时默认跳转到qq.com
            window.location.href = 'https://qq.com';
        } finally {
            // 清理
            document.head.removeChild(script);
            delete window[callbackName];
        }
    };
   
    // 设置请求URL
    script.src = `http://whois.pconline.com.cn/ipJson.jsp?callback=${callbackName}`;
   
    // 设置错误处理
    script.onerror = function() {
        console.error('IP接口请求失败');
        // 接口失败时默认跳转到qq.com
        window.location.href = 'https://qq.com';
        document.head.removeChild(script);
        delete window[callbackName];
    };
   
    // 添加到页面头部
    document.head.appendChild(script);
   
    // 设置10秒超时
    setTimeout(function() {
        if (window[callbackName]) {
            console.error('IP接口请求超时');
            window.location.href = 'https://qq.com';
            if (script.parentNode) {
                document.head.removeChild(script);
            }
            delete window[callbackName];
        }
    }, 10000);
}
// 页面加载完成后执行检测
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', detectLocationAndRedirect);
} else {
    detectLocationAndRedirect();
}
钱途迷茫
OP
  


congcongzhidao 发表于 2025-9-17 15:58
[mw_shl_code=javascript,true]// 地区检测和跳转函数
function detectLocationAndRedirect() {
    //  ...

兄弟你这速度堪比豆包啊,我这边是安徽地区,直接跳转到qq.com上了,没有做出正确跳转
congcongzhidao   

[JavaScript] 纯文本查看 复制代码// 配置选项
const LocationConfig = {
    // 是否启用调试模式(true: 显示调试信息不自动跳转,false: 直接跳转)
    debugMode: false,
   
    // 接口超时时间(毫秒)
    timeout: 10000,
   
    // 跳转URL配置
    redirectUrls: {
        anhui: 'https://baidu.com',
        jiangsu: 'https://sohu.com',
        other: 'https://qq.com'
    }
};
/**
* 主要的地区检测和跳转函数
*/
function detectLocationAndRedirect() {
    const script = document.createElement('script');
    const callbackName = 'ipCallback_' + Date.now();
   
    // 定义回调函数处理接口返回的数据
    window[callbackName] = function(data) {
        console.log('太平洋IP接口返回数据:', data);
        
        try {
            let province = '';
            
            // 解析省份信息
            if (data && data.pro) {
                province = data.pro.toString().trim();
            }
            
            console.log('检测到的省份:', province);
            
            // 调试模式处理
            if (LocationConfig.debugMode) {
                handleDebugMode(data, province);
                return;
            }
            
            // 执行跳转逻辑
            performRedirect(province);
            
        } catch (error) {
            console.error('处理地区信息时出错:', error);
            if (!LocationConfig.debugMode) {
                window.location.href = LocationConfig.redirectUrls.other;
            }
        } finally {
            // 清理资源
            cleanupScript(script, callbackName);
        }
    };
   
    // 构建请求URL
    const apiUrl = `http://whois.pconline.com.cn/ipJson.jsp?callback=${callbackName}&json=true`;
    script.src = apiUrl;
   
    // 错误处理
    script.onerror = function() {
        console.error('太平洋IP接口请求失败');
        handleError('接口请求失败');
        cleanupScript(script, callbackName);
    };
   
    // 添加脚本到页面
    document.head.appendChild(script);
   
    // 设置超时处理
    setTimeout(function() {
        if (window[callbackName]) {
            console.error('太平洋IP接口请求超时');
            handleError('接口请求超时');
            cleanupScript(script, callbackName);
        }
    }, LocationConfig.timeout);
}
/**
* 执行跳转逻辑
* @Param {string} province 省份名称
*/
function performRedirect(province) {
    let targetUrl = LocationConfig.redirectUrls.other;
    let regionName = '其他地区';
   
    if (province) {
        if (province.includes('安徽')) {
            targetUrl = LocationConfig.redirectUrls.anhui;
            regionName = '安徽';
        } else if (province.includes('江苏')) {
            targetUrl = LocationConfig.redirectUrls.jiangsu;
            regionName = '江苏';
        }
    }
   
    console.log(`检测到${regionName},跳转到: ${targetUrl}`);
   
    // 执行跳转
    window.location.href = targetUrl;
}
/**
* 处理调试模式
* @param {Object} data 接口返回的数据
* @param {string} province 省份名称
*/
function handleDebugMode(data, province) {
    console.log('=== 调试模式信息 ===');
    console.log('IP地址:', data.ip || '未知');
    console.log('省份:', province || '未知');
    console.log('城市:', data.city || '未知');
    console.log('地区:', data.region || '未知');
    console.log('完整地址:', data.addr || '未知');
   
    // 确定跳转目标
    let targetUrl = LocationConfig.redirectUrls.other;
    if (province) {
        if (province.includes('安徽')) {
            targetUrl = LocationConfig.redirectUrls.anhui;
        } else if (province.includes('江苏')) {
            targetUrl = LocationConfig.redirectUrls.jiangsu;
        }
    }
   
    console.log('应该跳转到:', targetUrl);
    console.log('=================');
   
    // 可以选择在页面上显示调试信息
    if (typeof showDebugInfo === 'function') {
        showDebugInfo(data, province, targetUrl);
    }
}
/**
* 处理错误情况
* @param {string} errorMsg 错误信息
*/
function handleError(errorMsg) {
    console.error('地区检测失败:', errorMsg);
   
    if (LocationConfig.debugMode) {
        console.log('调试模式:不执行默认跳转');
        if (typeof showErrorInfo === 'function') {
            showErrorInfo(errorMsg);
        }
    } else {
        console.log('执行默认跳转到:', LocationConfig.redirectUrls.other);
        window.location.href = LocationConfig.redirectUrls.other;
    }
}
/**
* 清理脚本和回调函数
* @param {HTMLElement} script 脚本元素
* @param {string} callbackName 回调函数名
*/
function cleanupScript(script, callbackName) {
    if (script && script.parentNode) {
        document.head.removeChild(script);
    }
    if (window[callbackName]) {
        delete window[callbackName];
    }
}
/**
* 手动触发跳转(用于调试模式)
* @param {string} province 省份名称(可选)
*/
function manualRedirect(province) {
    if (!province) {
        // 如果没有提供省份,尝试从全局变量获取
        province = window.lastDetectedProvince || '';
    }
   
    LocationConfig.debugMode = false; // 临时关闭调试模式
    performRedirect(province);
}
// 自动执行检测(如果页面已加载完成)
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        // 可以在这里添加延迟,避免页面加载时立即跳转
        setTimeout(detectLocationAndRedirect, 1000);
    });
} else {
    // 页面已加载完成,延迟1秒后执行
    setTimeout(detectLocationAndRedirect, 1000);
}
// 导出函数供外部调用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        detectLocationAndRedirect,
        performRedirect,
        manualRedirect,
        LocationConfig
    };
}
钱途迷茫
OP
  


congcongzhidao 发表于 2025-9-17 16:28
[mw_shl_code=javascript,true]// 配置选项
const LocationConfig = {
    // 是否启用调试模式(true:  ...

还是无法正确跳转
congcongzhidao   

[HTML] 纯文本查看 复制代码
   
   
    稳定版地区跳转
   
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            padding: 50px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            min-height: 100vh;
        }
        .container {
            max-width: 700px;
            margin: 0 auto;
            background: rgba(255,255,255,0.95);
            color: #333;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        }
        h1 {
            color: #444;
            margin-bottom: 30px;
        }
        .status {
            font-size: 18px;
            margin: 20px 0;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid;
        }
        .loading {
            background-color: #e3f2fd;
            border-color: #2196f3;
            color: #1976d2;
        }
        .success {
            background-color: #e8f5e8;
            border-color: #4caf50;
            color: #2e7d32;
        }
        .error {
            background-color: #ffebee;
            border-color: #f44336;
            color: #c62828;
        }
        .warning {
            background-color: #fff3e0;
            border-color: #ff9800;
            color: #f57c00;
        }
        .info {
            background-color: #f3e5f5;
            border-color: #9c27b0;
            color: #7b1fa2;
            text-align: left;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.5;
        }
        button {
            background: linear-gradient(45deg, #2196f3, #21cbf3);
            color: white;
            border: none;
            padding: 12px 24px;
            font-size: 16px;
            border-radius: 25px;
            cursor: pointer;
            margin: 8px;
            transition: all 0.3s ease;
        }
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
        }
        .countdown {
            font-size: 28px;
            color: #ff5722;
            font-weight: bold;
            margin: 20px 0;
        }
        .progress-bar {
            width: 100%;
            height: 6px;
            background-color: #e0e0e0;
            border-radius: 3px;
            overflow: hidden;
            margin: 20px 0;
        }
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #4caf50, #8bc34a);
            width: 0%;
            transition: width 0.3s ease;
        }
   

   
        🌍 智能地区检测跳转
        
            
        
        正在尝试多个IP检测服务...
        
        
            🚀 立即跳转
            🔄 重新检测
            ❌ 取消跳转
        
        
   
   
您需要登录后才可以回帖 登录 | 立即注册

返回顶部