如何通过jQuery实现阻止定位后移除浏览器定位图标并跳转页面?
解决浏览器定位图标在用户阻止后无法自动消失的问题
当用户阻止定位请求后,浏览器定位图标无法自动消失,核心原因是navigator.geolocation.getCurrentPosition的请求还没完成收尾处理就触发了页面跳转,导致浏览器来不及移除图标。
解决思路是在错误回调中延迟执行页面跳转,给浏览器足够时间完成定位请求的终止流程:
$(".in").click(function () { const options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }; function success(pos) { const crd = pos.coords; var lats = crd.latitude; var longs = crd.longitude; $.ajax({ type: "POST", url: "insert.php", data: { lats: lats, longs: longs, }, success: function (data) { // further code } }); } function error(err) { alert('Please refresh page and select allow to continue for location'); // 延迟100ms执行跳转,给浏览器时间清理定位图标 setTimeout(() => { window.location = window.location.href; }, 100); } navigator.geolocation.getCurrentPosition(success, error, options); });
原理说明
浏览器会在定位请求的回调函数执行完毕后,完成定位状态的清理(包括移除定位图标)。直接跳转页面会中断这个清理流程,延迟跳转能让浏览器先处理完定位请求的收尾工作,确保图标被正常移除。
内容的提问来源于stack exchange,提问作者virat sharma
相关产品推荐
相关产品推荐

