gpt4 book ai didi

javascript - 当蜂窝网络不可用时,geolocation.getCurrentPosition 不起作用

转载 作者:行者123 更新时间:2023-12-02 21:40:47 24 4
gpt4 key购买 nike

我正在开发一个应用程序,在这个应用程序中我想获取 getCurrentPosition。我已经创建了一个 PWA 应用程序并实现了离线模式。因此,当互联网可用时,互联网不可用时,这两种情况都可以正常工作,但当蜂窝网络不可用(飞行模式)时,geolocation.getCurrentPosition 函数将返回空值。

服务人员代码:-

var CACHE_NAME = 'geolocation_cache';
// Install a service worker
self.addEventListener('install', event => {
event.waitUntil( async function(){
let cache= await caches.open(CACHE_NAME)
await cache.addAll(
[
'/manifest.json',
'/geolocationoffline.html',
]
);
}())
});

// Update or Activate a service worker
self.addEventListener('activate', event =>{
event.waitUntil( async function(){
let cacheWhitelist = ['geolocation_cache'];
let cacheNames = await caches.keys();
await Promise.all(
cacheNames.map(element => {
if(cacheWhitelist.indexOf(element) === -1){
return caches.delete(element);
}
})
)
}())
});

// Cache and return requests
self.addEventListener('fetch', event => {
event.respondWith( async function(){
const availableCache= await caches.open('geolocation_cache');
if(event.request.url.indexOf('/geolocation') < 0){
const availableCache= await caches.open('geolocation_dynamic');
try{
const networkResponse = await fetch(event.request);
const cachedResponse = await availableCache.match(event.request);
if(cachedResponse) return cachedResponse;
const networkResponse = await fetch(event.request);
event.waitUntil(
availableCache.put(event.request, networkResponse.clone())
);
return networkResponse;
}
catch(err){
const availableCache= await caches.open('geolocation_cache');
let response=await availableCache.match('/geolocationoffline.html');
return response;
}
}
else{
return await fetch(event.request);
}
}())
});

离线页面:-

<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
</head>
<body>
<div id="root">
<h3>Geo Location Offline</h3>
<p class="time-info"></p>
<p class="page-info"></p>
</div>
<script>
navigator.geolocation.getCurrentPosition(function(position){
document.getElementsByClassName("page-info")[0].innerText=`lat=${position.coords.latitude} long=${position.coords.longitude}`;
document.getElementsByClassName("time-info")[0].innerText=`timeStamp=${position.timestamp}`;
});
</script>
</body>
</html>

最佳答案

这很正常。大多数设备在飞行模式下也会关闭 GPS 功能。

关于javascript - 当蜂窝网络不可用时,geolocation.getCurrentPosition 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60369257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com