Kotlin版PWA中getInstalledRelatedApps失效,求替代检测方案
针对你用Kotlin开发的WebView版PWA遇到的getInstalledRelatedApps返回空的问题,这里提供几个不依赖该API的检测方法:
1. 自定义User-Agent标识
在Kotlin的WebView配置中添加专属标识,网页端通过识别User-Agent判断是否处于你的应用内:
Kotlin端配置
webView.settings.userAgentString = "${webView.settings.userAgentString} YourPWA/1.0 (Kotlin)"
网页端检测代码
const isInstalled = navigator.userAgent.includes('YourPWA/1.0 (Kotlin)'); console.log(isInstalled ? '应用已安装' : '未在应用内');
2. 注入JS交互接口
通过WebView的JS桥注入本地方法,直接向网页暴露安装状态:
Kotlin端配置
class AppInstallStatusInterface { @JavascriptInterface fun isAppInstalled(): Boolean { return true // 当前处于应用内运行,固定返回true } } // 将接口注入WebView webView.addJavascriptInterface(AppInstallStatusInterface(), "AppBridge")
网页端调用代码
let isInstalled = false; if (window.AppBridge) { isInstalled = window.AppBridge.isAppInstalled(); } console.log(isInstalled ? '应用已安装' : '未在应用内');
3. 自定义URL Scheme检测
给你的Kotlin应用配置专属URL Scheme,网页端尝试唤起该Scheme判断应用是否存在:
Kotlin端配置(AndroidManifest.xml)
<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" /> <!-- 自定义专属Scheme,例如yourapp:// --> <data android:scheme="yourapp" /> </intent-filter> </activity>
网页端检测代码
function checkAppInstalled() { let isInstalled = false; const startTime = Date.now(); // 尝试唤起应用Scheme window.location.href = 'yourapp://check-install'; // 通过时间差判断是否唤起成功 setTimeout(() => { isInstalled = Date.now() - startTime >= 1000; console.log(isInstalled ? '应用已安装' : '未安装'); }, 1000); }
注意:URL Scheme方法需要配合用户点击事件触发(部分浏览器限制自动唤起),且会弹出系统询问框让用户确认是否打开应用。
内容的提问来源于stack exchange,提问作者pmiranda
相关产品推荐
相关产品推荐

