产品提了个需求,通过手机网页判断是否安装了自己公司 app,如果安装了则拉起 app,没有安装则跳转到下载页。
经过各种查阅资料尝试总结了一个还算可以的办法。
拉起 app 的原理就是 js 和原生统一好一个地址,例如(qiyimobile://self/qiyi.madeindexpage)。然后浏览器发起请求,如果 app 安装了则会拦截这个请求并且打开。
下面是安卓代码配置。其实 scheme 和 host 要和 js 这边统一
- <span style="font-size:18px;"><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="qiyimobile"
- android:host="self/qiyi.madeindexpage"
- android:pathPrefix="/**">
- </data>
- </intent-filter></span>
js 这边稍微麻烦一些。如果只拉起 app 比较简单,直接通过 a 连接或者 window.location.href="**" 即可。不过这里有个问题,就是有些手机在未安装 app 的时候会识别我们之前定的那个协议尝试打开这个网页,当然会报找不到网页。这里用 iframe 的方式兼容性稍好。
- var ifr = document.createElement('iframe');
- ifr.src = 'qiyimobile://self/qiyi.madeindexpage';
- document.body.appendChild(ifr);
当手机未安装 app 时应该跳转到下载页,很多人说延时一下直接跳转就行,如下
- window.location.href="打开地址"
- setTimeout(function() {
- window.location.href="下载地址"
- }, 500);
当然这样也是有问题的,因为有的手机拉起 app 也不会自动清除定时器,即无论是否安装 app,页面都会在 500ms 后跳转到下载页。所以判断是否需要跳转到下载页是最麻烦的事。最终尝试如下是比较好的解决方法。
设置一个初始时间,打开拉起 app 地址后有个结束时间,计算两者之差,当差大于一定时间是说明安装了 app,当差很小时说明没有打开 app,需要跳转到下载页。
最终代码如下
- downloadapp.addEventListener('click', function() {
- var start = new Date();//记录初始时间
- var t = 500;
- var ifr = document.createElement('iframe');
- ifr.src = 'qiyimobile://self/qiyi.madeindexpage';//打开app
- document.body.appendChild(ifr);
- ifr.onload = function() {
- };
- ifr.style.display='none';
- setTimeout(function() {
- document.body.removeChild(ifr);
- var end = new Date();//记录结束时间
- console.log(end - start)
- if (end - start <= (t + 30)) {//两者之差小于30ms时跳转到下载页
- window.location.href = "https://www.baidu.com"
- }
- }, t);
- })
来源: http://www.cnblogs.com/ytu2010dt/p/6429376.html