我需要知道用户的浏览器或操作系统上是否有与协议关联的导航程序
geo:
我的链接是这样的:
<a href="geo:51.5125509,-0.2190250">Address</a>
以前,我只是检查用户是否在移动设备上,在这种情况下,打开链接。如果在桌面上,链接已更改为
https://www.openstreetmap.org/directions?to=51.5125509,-0.2190250
.
但是,用户可以在桌面上为给定的协议注册默认网站或程序,所以我想更改我的功能。
我尝试过测试
navigator.registerProtocolHandler('geo', 'https://www.example.com/%s', 'Test Geo Handler');
但它必然会触发权限模式,并且实际上并没有告诉我需要什么。
编辑:我已经检查过这些问题,但就我而言,这不是自定义协议,所以我想我可能有机会。
navigator.registerProtocolHandler()
方法允许Web应用程序将自己注册为特定协议的可能处理程序,但它没有提供一种方法来检查是否已经为协议注册了任何处理程序而不触发权限模式。
因此,您可能会考虑一种实用的方法:尝试导航或打开
geo:
链接并优雅地处理任何错误或后备。但是,对于您的特定用例,您可以通过根据设备类型提供选项或允许用户选择他们喜欢的导航方法来增强用户体验。
继续使用设备检测来提供合理的默认值。 移动设备更有可能拥有用于
geo:
链接的本机处理程序。
对于桌面用户,您可以提供一个选择,而不是直接更改
geo:
链接。显示一个模式或下拉菜单,允许桌面用户选择在网络上的地图服务(如 OpenStreetMap 或 Google 地图)中打开链接或尝试使用注册程序直接打开它。
<a href="#" onclick="handleGeoLink('51.5125509,-0.2190250')">Address</a>
<script>
function handleGeoLink(coords) {
// Detect mobile devices (simple check, consider using a library for a robust solution)
if (/Mobi|Android/i.test(navigator.userAgent)) {
// Directly attempt to open geo: link on mobile devices
window.location.href = `geo:${coords}`;
} else {
// For desktop, offer choices or directly navigate to a web map service
// Example: open a modal or use a dropdown to let the user choose
if (confirm("Do you want to open this address in a web map service?")) {
window.open(`https://www.openstreetmap.org/directions?to=${coords}`, '_blank');
} else {
// Optionally, try to open the geo: protocol directly
// That may not work if no handler is registered, but there is no direct way to check
window.location.href = `geo:${coords}`;
}
}
}
</script>
再次强调,这不是直接检测
geo:
协议处理程序是否已在桌面上注册,而是通过提供选择来改善用户体验。