You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发简易天气爬虫时浏览器未触发地理位置权限请求的问题求助

开发简易天气爬虫时浏览器未触发地理位置权限请求的问题求助

大家好,我正在开发一个简易的天气数据抓取工具,但碰到了一个棘手的问题——浏览器始终不会弹出请求用户地理位置权限的提示,我试了两种不同的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 13:52:38