开发简易天气爬虫时浏览器未触发地理位置权限请求的问题求助
开发简易天气爬虫时浏览器未触发地理位置权限请求的问题求助
大家好,我正在开发一个简易的天气数据抓取工具,但碰到了一个棘手的问题——浏览器始终不会弹出请求用户地理位置权限的提示,我试了两种不同的JS写法都没解决,想请大家帮忙看看问题出在哪?
第一种写法(使用Permission API申请权限)
require('dotenv').config(); const apiKey = process.env.API_KEY; // onload event listener for api: window.addEventListener('load', () => { let lon; let lat; // asks permission to access users location: navigator.permissions.request({ name: 'geolocation' }) .then((permission) => { if (permission.state === 'granted'){ navigator.geolocation.getCurrentPosition((position) => { try { let lon = position.coords.longitude; let lat = position.coords.latitude; const locationData = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}`; fetch(locationData).then((response) => { return response.json(); }) .catch((error) => { console.error(error); }); } catch (error) { console.error(error); } }); } }); });
第二种写法(直接调用getCurrentPosition)
require('dotenv').config(); const apiKey = process.env.API_KEY; // onload event listener for api: window.addEventListener('load', () => { let long; let lat; // accesses location of user: if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position) => { long = position.coords.longitude; lat = position.coords.latitude; const locationData = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${apiKey}`; fetch(locationData).then((response) => { return response.json(); }); } )} });
我已经尝试过的解决方法:
- 切换到Safari打开Live Server,但依然没有触发位置权限请求
- 确认Chrome和Safari在我的Mac系统中已经获得了位置访问权限
- 修正了locationData URL中的字符串插值错误(一开始模板字符串的变量没写对)
- 给核心逻辑加上了try-catch块
- 重新生成了OpenWeatherMap的API密钥
- 加入了
navigator.permissions.request主动申请权限,但问题依旧
始终存在的错误信息:
浏览器控制台报错:
main.js:1 Uncaught ReferenceError: require is not defined at main.js:1:1
VS Code终端运行时报错:
window.addEventListener('load', () => { ^ ReferenceError: window is not defined.
不管用不用Permission API,这两个错误都会出现。
备注:内容来源于stack exchange,提问作者emsleyd
相关产品推荐
相关产品推荐

