如何在网站添加显示上次访问城市及国家的提示信息?
实现用户上次访问城市/国家的提示功能
核心思路
- 放弃依赖用户授权的
getCurrentPosition(),改用IP地址匹配地理位置的方式(无需用户授权,更适合记录上次访问信息) - 用
localStorage存储用户上次访问的位置数据,页面加载时读取并展示
具体实现步骤
1. 通过IP获取地理位置
调用免费的IP地理服务接口,获取当前访问者的城市和国家信息:
async function getLocationByIP() { try { const response = await fetch('https://ipapi.co/json/'); const data = await response.json(); return { city: data.city || '未知城市', country: data.country_name || '未知国家' }; } catch (error) { console.error('获取位置失败:', error); return { city: '未知城市', country: '未知国家' }; } }
2. 存储与读取上次访问信息
用localStorage持久化存储位置数据,页面加载时优先读取本地历史数据:
// 存储上次访问位置 function saveLastVisitLocation(location) { localStorage.setItem('lastVisitLocation', JSON.stringify(location)); } // 读取上次访问位置 function getLastVisitLocation() { const stored = localStorage.getItem('lastVisitLocation'); return stored ? JSON.parse(stored) : null; }
3. 展示右下角提示框
页面初始化时,读取历史位置并创建固定在右下角的提示元素:
async function initVisitPrompt() { const lastLocation = getLastVisitLocation(); let currentLocation; if (lastLocation) { // 有历史记录,显示上次访问信息 showPrompt(`欢迎回来!上次访问来自:${lastLocation.city}, ${lastLocation.country}`); // 同步更新为当前位置 currentLocation = await getLocationByIP(); saveLastVisitLocation(currentLocation); } else { // 首次访问,获取当前位置并存入 currentLocation = await getLocationByIP(); saveLastVisitLocation(currentLocation); showPrompt(`欢迎!当前访问来自:${currentLocation.city}, ${currentLocation.country}`); } } // 创建并显示提示框 function showPrompt(message) { const promptEl = document.createElement('div'); promptEl.style.cssText = ` position: fixed; bottom: 20px; right: 20px; padding: 12px 20px; background: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.15); font-size: 14px; z-index: 9999; `; promptEl.textContent = message; document.body.appendChild(promptEl); // 3秒后自动隐藏(可选) setTimeout(() => { promptEl.style.opacity = '0'; promptEl.style.transition = 'opacity 0.3s'; setTimeout(() => document.body.removeChild(promptEl), 300); }, 3000); } // 页面加载完成后执行 window.addEventListener('load', initVisitPrompt);
为什么不用getCurrentPosition()?
- 需要用户手动授权,大部分用户会拒绝,导致无法获取位置
- 返回的是实时地理位置,而非用户上次访问的记录,不符合需求
- IP地理方式无需授权,更适合记录用户的访问轨迹信息
内容的提问来源于stack exchange,提问作者LUIS CARLOS
相关产品推荐
相关产品推荐

