JS如何检测手机上APP是否安装的情况

分类:Javascript| 发布:佚名| 查看: | 发表时间:2015/11/20
我们在浏览网页的时候,你会看到一个网页下面漂浮着一个提示框“打开APP”或者“下载APP的字样”,如果你的手机已经安装过这个APP,那么网页会提示“打开APP”,如果没有安装,那就会提示“下载APP的字样” 这个从技术角度是如何去实现的呢?下面我给大家分享这块技术,去年公司给国际动漫节做项目的时候,客户就提到这个需求,在点击网页企业的时候 那么直接打开APP(如果已经安装了) 如果没有安装过,直接打开APP页面
 
下面我把这块的源码分享一下
if (navigator.userAgent.match(/android/i)) {
// 通过iframe的方式试图打开APP,如果能正常打开,会直接切换到APP,并自动阻止a标签的默认行为
// 否则打开a标签的href链接
var isInstalled;
//下面是安卓端APP接口调用的地址,自己根据情况去修改
var ifrSrc = 'AppProtocolHeader://camnpr? type=0&id=${com.id}&phone_num=${com.phone_num}';
var ifr = document.createElement('iframe');
ifr.src = ifrSrc;
ifr.style.display = 'none';
ifr.onload = function() {
// alert('Is installed.');
isInstalled = true;
alert(isInstalled);
document.getElementById('openApp0').click();};
ifr.onerror = function() {
// alert('May be not installed.');
isInstalled = false;
alert(isInstalled);
}
document.body.appendChild(ifr);
setTimeout(function() {
document.body.removeChild(ifr);
},1000);
}

//ios判断
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i))
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
//Animation://com.camnpr.animation
var isInstalled;
//var gz = '{"comName":"${com.short_name}","comID":"${com.id}","comPhoneNum":"${com.phone_num}","type":"0"}';
//var jsongz =JSON.parse(gz);

//下面是IOS调用的地址,自己根据情况去修改
var ifrSrc = 'AppProtocolHeader://?comName=${com.short_name}&comID=${com.id}&comPhoneNum=${com.phone_num}&type=0';var ifr = document.createElement('iframe');
ifr.src = ifrSrc;
ifr.style.display = 'none';
ifr.onload = function() {
// alert('Is installed.');
isInstalled = true;
alert(isInstalled);
document.getElementById('openApp1').click();};
ifr.onerror = function() {
// alert('May be not installed.');
isInstalled = false;
alert(isInstalled);
}
document.body.appendChild(ifr);
setTimeout(function() {
document.body.removeChild(ifr);
},1000);
}
}
大家在做的过程中需要注意两个问题:
1、接口地址一定要写对,大家可以查一下schema协议,通过这个协议调用的
2、在做用安卓的时候 如果用微信扫一扫或者QQ浏览器扫码功能的时候
使用上面的协议会存在问题的就是必须用APK上架到腾讯应用市场上去
365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/javascript/2200.html