js deeplink 实现
实现 JavaScript Deeplink 的方法
使用 window.location 或 window.open 进行页面跳转
通过修改 window.location.href 或调用 window.open() 可以直接跳转到目标 URL。适用于普通的网页跳转场景。
window.location.href = 'myapp://path/to/content';
// 或
window.open('myapp://path/to/content', '_blank');
检测是否成功打开应用(超时回退方案)
如果 Deeplink 未成功打开应用(如移动端未安装应用),可通过 setTimeout 回退到备用页面(如应用商店)。
const deeplinkUrl = 'myapp://profile/123';
const fallbackUrl = 'https://appstore.com/myapp';
window.location.href = deeplinkUrl;
setTimeout(() => {
if (!document.hidden) {
window.location.href = fallbackUrl;
}
}, 1000); // 延迟 1 秒检测
使用 navigator.userAgent 区分平台
根据用户设备类型(iOS/Android)生成不同的 Deeplink 格式。例如 iOS 使用 universal links,Android 使用 intent。
const isAndroid = /android/i.test(navigator.userAgent);
const isIOS = /iphone|ipad/i.test(navigator.userAgent);
if (isAndroid) {
window.location.href = 'intent://path#Intent;scheme=myapp;package=com.myapp;end';
} else if (isIOS) {
window.location.href = 'myapp://path/to/content';
}
处理 Universal Links(iOS)
对于 iOS 9+,优先使用 Universal Links(HTTPS 格式的 Deeplink),需在服务端配置 apple-app-site-association 文件。
// 直接跳转 Universal Link
window.location.href = 'https://example.com/path/to/content';
动态创建 iframe 触发 Deeplink(兼容性方案)
部分浏览器限制直接跳转,可通过动态创建隐藏的 iframe 触发 Deeplink。
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = 'myapp://path/to/content';
document.body.appendChild(iframe);
setTimeout(() => document.body.removeChild(iframe), 100);
注意事项
- 协议注册:确保原生应用已注册自定义协议(如
myapp://)或 Universal Links。 - 用户交互限制:部分浏览器要求 Deeplink 必须在用户点击事件内触发(如
onClick)。 - 错误处理:始终提供回退逻辑(如应用商店链接或网页版替代方案)。
- 测试工具:使用调试工具(如 iOS 的
Console.app或 Android 的adb logcat)验证 Deeplink 是否正常触发。







