js deeplink 实现
什么是 Deeplink
Deeplink(深度链接)是一种允许用户通过点击链接直接跳转到应用内特定页面的技术。在 Web 开发中,可以通过 JavaScript 实现 Deeplink 功能,引导用户从网页跳转到移动应用内的指定位置。
实现 Deeplink 的基本原理
Deeplink 的实现通常依赖于 URI Scheme 或 Universal Links(iOS)/ App Links(Android)。URI Scheme 是一种自定义的 URL 协议,例如 myapp://home,而 Universal Links 和 App Links 则使用标准的 HTTP/HTTPS 链接。
使用 URI Scheme 实现 Deeplink
URI Scheme 是较早的 Deeplink 实现方式,通过自定义协议打开应用。

// 尝试通过 URI Scheme 打开应用
function openAppWithURIScheme() {
const deeplink = 'myapp://home';
window.location.href = deeplink;
// 如果应用未安装,跳转到应用商店
setTimeout(function() {
if (!document.hidden) {
window.location.href = 'https://apps.apple.com/app/id123456'; // iOS
// 或 window.location.href = 'https://play.google.com/store/apps/details?id=com.example.app'; // Android
}
}, 500);
}
使用 Universal Links / App Links 实现 Deeplink
Universal Links(iOS)和 App Links(Android)使用标准 HTTP/HTTPS 链接,无需自定义协议。
// 使用 Universal Links / App Links 打开应用
function openAppWithUniversalLink() {
const deeplink = 'https://example.com/home';
window.location.href = deeplink;
// 如果应用未安装,跳转到应用商店
setTimeout(function() {
if (!document.hidden) {
window.location.href = 'https://apps.apple.com/app/id123456'; // iOS
// 或 window.location.href = 'https://play.google.com/store/apps/details?id=com.example.app'; // Android
}
}, 500);
}
检测应用是否安装
为了优化用户体验,可以检测应用是否安装,再决定是否跳转到应用商店。

// 检测应用是否安装
function checkAppInstalled() {
const deeplink = 'myapp://home';
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = deeplink;
document.body.appendChild(iframe);
setTimeout(function() {
document.body.removeChild(iframe);
if (!document.hidden) {
window.location.href = 'https://apps.apple.com/app/id123456'; // iOS
// 或 window.location.href = 'https://play.google.com/store/apps/details?id=com.example.app'; // Android
}
}, 500);
}
兼容性处理
不同平台(iOS、Android)对 Deeplink 的支持可能不同,需要进行兼容性处理。
// 根据平台选择不同的 Deeplink 方式
function openDeeplink() {
const isiOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
const deeplink = isiOS ? 'https://example.com/home' : 'myapp://home';
window.location.href = deeplink;
setTimeout(function() {
if (!document.hidden) {
const storeUrl = isiOS
? 'https://apps.apple.com/app/id123456'
: 'https://play.google.com/store/apps/details?id=com.example.app';
window.location.href = storeUrl;
}
}, 500);
}
使用第三方库简化实现
为了简化 Deeplink 的实现,可以使用第三方库如 react-deep-link 或 universal-link。
// 使用 react-deep-link 示例
import { DeepLink } from 'react-deep-link';
function App() {
return (
<DeepLink
appUrl="myapp://home"
storeUrl={{
ios: 'https://apps.apple.com/app/id123456',
android: 'https://play.google.com/store/apps/details?id=com.example.app'
}}
>
<button>Open App</button>
</DeepLink>
);
}
注意事项
- URI Scheme 的限制:某些浏览器可能会阻止 URI Scheme 的跳转,尤其是在 iOS 的 Safari 中。
- Universal Links 的配置:Universal Links 需要在服务器上配置
apple-app-site-association文件,App Links 需要配置assetlinks.json文件。 - 延迟跳转:检测应用是否安装通常需要设置延迟跳转,避免直接跳转到应用商店。
通过以上方法,可以在 JavaScript 中实现 Deeplink 功能,引导用户从网页跳转到应用内特定页面。






