如何实现手机浏览器访问指定URL时唤起已安装的React Native应用
实现方案
以下两种是经过生产验证的可行方案,可根据你的业务场景选择,也可以组合使用覆盖全版本设备:
方案1:自定义Scheme深度链接 + 延时兜底跳转
该方案适配所有Android版本,配置逻辑简单。
配置步骤
- React Native端配置
在Android项目的AndroidManifest.xml中添加唤起App的intent-filter配置:
<activity android:name=".MainActivity" <!-- 其他原有配置保持不变 --> > <!-- 新增深度链接唤起配置 --> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="myapp" <!-- 自定义的协议名,可自行修改 --> android:host="open" /> <!-- 自定义的host,可自行修改 --> </intent-filter> </activity>
配置完成后RN端通过自带的Linking库即可接收唤起链接的参数:
import { Linking } from 'react-native'; // 处理App冷启动时的唤起链接 Linking.getInitialURL().then(url => { if (url) { // 自行解析url参数,跳转对应业务页面 } }); // 处理App后台运行时的唤起链接 Linking.addEventListener('url', ({ url }) => { // 处理url逻辑 });
- Web端逻辑实现
页面加载完成后先尝试唤起App,若指定时间内未唤起则自动跳转Play商店:
window.addEventListener('load', () => { // 自定义Scheme唤起链接,可携带自定义参数 const appLink = 'myapp://open?source=web_home'; // Play商店应用下载页地址 const downloadLink = 'market://details?id=你的应用包名'; window.location.href = appLink; // 300ms后未唤起则跳下载页,时长可根据实际情况调整 const timer = setTimeout(() => { window.location.href = downloadLink; }, 300); // 页面被隐藏说明App已成功唤起,清除跳转定时器 document.addEventListener('visibilitychange', () => { if (document.hidden) clearTimeout(timer); }); window.addEventListener('beforeunload', () => clearTimeout(timer)); });
优缺点
- 优点:全Android版本兼容,配置成本低
- 缺点:部分浏览器会弹出是否允许打开App的确认框,高版本Chrome可能拦截自动跳转的自定义Scheme
方案2:Android App Links(官方推荐,体验最优)
该方案是谷歌官方推出的域名关联唤醒方案,无需确认弹窗,不会被浏览器拦截。
配置步骤
- React Native端配置
在AndroidManifest.xml中添加App Links的intent-filter配置:
<intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="https" android:host="mywebpage.com" <!-- 替换为你的站点域名 --> android:pathPrefix="/*" /> <!-- 匹配全站路径,可按需缩小范围 --> </intent-filter>
- Web端域名验证配置
在你的Web站点根目录下新增.well-known/assetlinks.json文件,内容如下,替换为你自己的应用包名和签名指纹:
[{ "relation": ["delegate_permission/common.handle_all_urls"], "target": { "namespace": "android_app", "package_name": "你的应用包名", "sha256_cert_fingerprints": ["你的应用签名SHA256指纹"] } }]
文件需要支持公网访问,且不能有跨域限制,谷歌会自动验证该域名的所有权,验证通过后即可生效。
- Web端逻辑
不需要额外写唤起App的JS逻辑,用户访问https://mywebpage.com时系统会自动判断:
- 已安装App:直接唤起App
- 未安装App:正常打开Web页面,你可以在Web页面中自行引导用户跳转到Play商店下载
优缺点
- 优点:系统级支持,无弹窗无拦截,用户体验最优
- 缺点:仅支持Android 6.0及以上版本,需要额外做域名所有权验证
最佳实践
两种方案可以组合使用:Android 6.0以上走App Links方案,低版本走自定义Scheme方案,覆盖全设备场景,同时兼顾体验和兼容性。
内容的提问来源于stack exchange,提问作者Vasanth kumar
相关产品推荐
相关产品推荐

