如何在网站顶部显示智能应用横幅并隐藏WebView内的横幅
这个问题太常见了——用户都已经在你的App里了,还弹出引导下载的横幅确实有点尴尬。别担心,我们可以通过检测当前环境是否是安卓WebView,来控制横幅只在移动浏览器中显示。
核心思路
安卓系统的WebView在请求网页时,会在User-Agent(用户代理)字符串中带上特定标识,比如WebView或者你App的包名(如果是自定义WebView的话)。我们可以通过解析这个字符串判断当前环境是不是WebView,然后只在非WebView环境初始化SmartBanner。
具体实现步骤
1. 添加WebView检测函数
先写一个简单的函数,用来判断当前是否是安卓WebView:
function isAndroidWebView() { const userAgent = navigator.userAgent.toLowerCase(); // 检测标准WebView标识,同时排除Chrome浏览器的误判 return userAgent.includes('webview') && !userAgent.includes('chrome'); }
小提示:部分Chrome浏览器的UA也会包含
WebView字段,但通常会同时带有chrome标识,所以我们通过排除这个字段,确保只识别安卓App内的WebView。
2. 修改SmartBanner初始化逻辑
把原来的初始化代码放在条件判断里,只有当不是WebView的时候才执行:
<script src="assets/js/smart-app-banner.js"></script> <script type="text/javascript"> function isAndroidWebView() { const userAgent = navigator.userAgent.toLowerCase(); return userAgent.includes('webview') && !userAgent.includes('chrome'); } // 仅在非安卓WebView环境下初始化横幅 if (!isAndroidWebView()) { new SmartBanner({ daysHidden: 15, daysReminder: 90, appStoreLanguage: 'us', title: 'Winnova', author: 'Starcut LLC', button: 'VIEW', store: { ios: 'On the App Store', android: 'In Google Play', windows: 'In Windows store' }, price: { ios: 'FREE', android: 'FREE', windows: 'FREE' } // 其他配置项保持不变 }); } </script>
额外优化(可选)
如果你的App使用了自定义WebView,还可以在安卓原生代码中给WebView设置专属标识,比如:
webView.getSettings().setUserAgentString(webView.getSettings().getUserAgentString() + " WinnovaApp");
然后修改检测函数,专门识别这个标识,进一步提升判断精准度:
function isAndroidWebView() { const userAgent = navigator.userAgent.toLowerCase(); return userAgent.includes('winnovaapp') || (userAgent.includes('webview') && !userAgent.includes('chrome')); }
内容的提问来源于stack exchange,提问作者Mizlul
相关产品推荐
相关产品推荐

