React Native中实现:点击链接已装APP则打开,否则跳转Google Play
在React Native中实现「APP唤起/跳转商店」的深度链接方案
一、配置React Native应用的深度链接
Android端配置
打开android/app/src/main/AndroidManifest.xml,在主Activity的<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" /> <!-- 替换为你的自定义scheme,例如 myapp:// --> <data android:scheme="myapp" /> <!-- 可选:配置关联域名(用于App Links,避免浏览器弹窗) --> <data android:host="yourdomain.com" android:pathPrefix="/openapp" /> </intent-filter>
如果使用App Links,需在你的域名下放置/.well-known/assetlinks.json文件,格式需符合Android官方验证规范,用于证明域名与APP的关联关系。
iOS端配置
打开ios/YourAppName/Info.plist,添加URL Types配置:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>myapp</string> <!-- 自定义scheme --> </array> </dict> </array>
如需使用Universal Links,需在Apple Developer后台配置关联域名,并在Info.plist中添加对应配置项。
二、React Native中处理唤起链接
使用React Native内置的Linking API监听并处理深度链接:
import { Linking, useEffect } from 'react-native'; useEffect(() => { // 处理APP已在前台时的链接唤起 const handleDeepLink = ({ url }) => { // 解析URL并跳转至对应页面 console.log('收到唤起链接:', url); // 示例:navigation.navigate('TargetScreen', { data: url }); }; // 注册链接监听 const subscription = Linking.addEventListener('url', handleDeepLink); // 检查APP启动时是否来自深度链接 Linking.getInitialURL().then(url => { if (url) handleDeepLink({ url }); }); return () => subscription.remove(); }, []);
三、网页端跳转逻辑(核心实现)
在你的网页中通过JavaScript实现「优先唤起APP,失败则跳转Google Play」的逻辑:
function openAppOrRedirect() { const appSchemeLink = 'myapp://openapp'; // 自定义scheme链接 const playStoreLink = 'https://play.google.com/store/apps/details?id=com.your.app.package'; // 替换为你的APP包名 // 通过iframe尝试唤起APP(兼容部分浏览器) const iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = appSchemeLink; document.body.appendChild(iframe); // 设置超时,若唤起失败则跳转商店 setTimeout(() => { document.body.removeChild(iframe); window.location.href = playStoreLink; }, 1500); // 同时直接尝试打开scheme链接 window.location.href = appSchemeLink; }
在网页中绑定触发按钮:
<button onclick="openAppOrRedirect()">打开我的应用</button>
四、关键注意事项
- 不同浏览器对scheme唤起的处理逻辑有差异,超时时间建议设置在1000-2000ms之间,避免误跳转。
- Android App Links和iOS Universal Links需要完成域名验证,能提供无弹窗的流畅唤起体验。
- 测试时需分别验证「APP已安装」和「未安装」两种场景的跳转逻辑是否正常。
内容的提问来源于stack exchange,提问作者Aishwarya Gupta
相关产品推荐
相关产品推荐

