如何通过JavaScript解决Google Earth动态URL跳转至历史保存位置问题
问题描述
用JavaScript通过动态URL打开Google Earth Web指定坐标,初期功能正常,但一段时间后,页面Cookie保存的历史位置会覆盖URL中的目标坐标,导致跳转至历史位置而非指定地点。手动清除Google Earth的Cookie可恢复功能,但需要通过代码实现自动解决,无需用户手动操作。
原代码片段
window.open(`https://earth.google.com/web/search/${coords[0]},+${coords[1]}/@${coords[0]},${coords[1]},196.55454222a,112.74878798d,35y,0h,0t,0r`, '_blank');
解决方案
1. 添加URL参数强制忽略Cookie
Google Earth Web支持force=1参数,可强制按照URL内的坐标加载内容,忽略Cookie保存的历史位置。修改后的代码如下:
window.open(`https://earth.google.com/web/search/${coords[0]},+${coords[1]}/@${coords[0]},${coords[1]},196.55454222a,112.74878798d,35y,0h,0t,0r?force=1`, '_blank');
这是最简便且有效的方法,优先推荐使用。
2. 用无痕模式打开窗口
如果force参数失效,可尝试用无痕窗口打开目标链接。无痕模式默认不加载本地Cookie,能避免历史位置干扰,但部分浏览器可能会拦截自动弹出的无痕窗口,需用户授权允许弹窗:
// 创建无痕窗口(不同浏览器支持略有差异) const incognitoWindow = window.open('', '_blank', 'noopener,noreferrer,incognito'); if (incognitoWindow) { incognitoWindow.location.href = `https://earth.google.com/web/search/${coords[0]},+${coords[1]}/@${coords[0]},${coords[1]},196.55454222a,112.74878798d,35y,0h,0t,0r`; }
3. 清除Google Earth相关Cookie(受跨域限制)
通过JavaScript清除当前域名下的Google Earth关联Cookie,但仅当你的页面与Google Earth Web同域名时才能生效,跨域场景下无法操作。示例代码:
// 清除指定前缀的Google Earth相关Cookie function clearEarthCookies() { const cookies = document.cookie.split(';'); for (let cookie of cookies) { const eqPos = cookie.indexOf('='); const name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim(); // 匹配Google Earth相关Cookie名(可根据实际情况调整) if (name.startsWith('GE_') || name.startsWith('googleearth_')) { document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`; } } } // 先清除Cookie,再打开目标窗口 clearEarthCookies(); window.open(`https://earth.google.com/web/search/${coords[0]},+${coords[1]}/@${coords[0]},${coords[1]},196.55454222a,112.74878798d,35y,0h,0t,0r`, '_blank');
内容的提问来源于stack exchange,提问作者Spect
相关产品推荐
相关产品推荐

