修改Facebook浏览器跳转脚本 支持Instagram及iPhone端跳转指定外部浏览器
功能扩展实现方案
逻辑调整说明
- 新增3个环境判断函数,分别识别iOS设备、安卓设备、Instagram内置浏览器
- 匹配规则完全覆盖需求:
- 安卓端Facebook/Instagram内置浏览器统一跳转Chrome
- iOS端Facebook/Instagram内置浏览器统一跳转Safari
- 优化原有链接处理逻辑,改用原生URL API解析地址,避免带参数、带锚点的特殊链接处理出错
完整可运行代码
<script> // 设备与内置浏览器判断 function isIos() { return /iPhone|iPad|iPod/i.test(navigator.userAgent); } function isAndroid() { return /Android/i.test(navigator.userAgent); } function isFacebookApp() { const ua = navigator.userAgent || navigator.vendor || window.opera; return ua.indexOf("FBAV") > -1 || ua.indexOf("FBAN") > -1; } function isInstagramApp() { const ua = navigator.userAgent || navigator.vendor || window.opera; return ua.indexOf("Instagram") > -1; } // 跳转主逻辑 if (isFacebookApp() || isInstagramApp()) { const currentUrl = new URL(location.href); const scheme = currentUrl.protocol.replace(':', ''); const noWwwHost = currentUrl.host.replace(/^www\./, ''); const fullPath = noWwwHost + currentUrl.pathname + currentUrl.search + currentUrl.hash; if (isAndroid()) { // 安卓跳转Chrome逻辑,沿用原有intent协议 const chromeLink = `intent://${fullPath}#Intent;scheme=${scheme};package=com.android.chrome;end`; window.location.href = chromeLink; } else if (isIos()) { // iOS无需特殊协议,直接赋值当前地址即可触发系统唤起Safari window.location.href = location.href; } } </script>
适配说明
- iOS端触发跳转后会自动弹出系统弹窗询问是否跳转Safari,符合iOS系统的隐私权限规范
- 若安卓设备未安装Chrome,会自动跳转Google Play的Chrome下载页,无需额外兼容逻辑
- 原有去除www前缀的逻辑保留,不会影响原有业务的链接规则
内容的提问来源于stack exchange,提问作者Khalid Mayson
相关产品推荐
相关产品推荐

