利用 html js判断 客户端是否安装了某个app 安装了就打开 否则跳转到gp

三种方式 

方式一:简单的进行打开app,延时操作若未打开直接跳gp

function isInstalled(){
        var urlFrag = 'somepars';
        var the_href = 'market://****';//获得下载链接
        window.location.href = "appname://start" + urlFrag;//打开某手机上的某个app应用
        setTimeout(function(){
            window.location.href = the_href;//如果超时就跳转到app下载页
        },800);
    }

方式二 :添加 iframe

function isInstalled() {
        var timeout, t = 1000,
             hasApp = true,
             urlFrag = 'somepars';
        url = "appname://start" + urlFrag ;
         var openScript = setTimeout(function() {
             if (!hasApp) {
                 var durl = 'market://******';
                 window.location.href = durl;
             }
             document.body.removeChild(ifr);
         }, 2000)

         var t1 = Date.now();
         var ifr = document.createElement("iframe");
         ifr.setAttribute('src', url);
         ifr.setAttribute('style', 'display:none');
         document.body.appendChild(ifr);
         timeout = setTimeout(function() {
             var t2 = Date.now();
             if (!t1 || t2 - t1 < t + 100) {
                 hasApp = false;
             }
        }, t);
    }

方式三:利用a标签,经过验证浏览器对iframe的方法支持率不高,而且同一个浏览器也会有时而能打开时而打不开的情况发生,经验证将iframe替换为a标签支持率很高

function openAppGp(ap, gp) {
    //检查app是否打开
    function checkOpen(cb) {
        var _clickTime = +(new Date());
        function check(elsTime) {
            if (elsTime > 2000 || document.hidden || document.webkitHidden) {
                cb(1);
            } else {
                cb(0);
            }
        }
        //启动间隔20ms运行的定时器,并检测累计消耗时间是否超过3000ms,超过则结束
        var _count = 0, intHandle;
        intHandle = setInterval(function () {
            _count++;
            var elsTime = +(new Date()) - _clickTime;
            if (_count >= 50 || elsTime > 2000) {
                clearInterval(intHandle);
                check(elsTime);
            }
        }, 20);
    }
    //在iframe 中打开APP
    const link = document.createElement('a');
	document.body.appendChild(link);
	link.setAttribute('href', ap);
	link.style.display = 'none';
	link.click();
    // if (1) {
    checkOpen(function (opened) {//checkOpen中的cbk参数 = function (opened)
        if (opened == 0) {
            //用户没有安装app 可以请求下载地址并跳转 跳转方法:window.location.href 即可
            window.location.href = gp;   
        } else if (opened == 1) {
            //用户打开了app  用户有安装app 
            console.log("Opend app");
        }
    });
    // }

    setTimeout(function () {
        document.body.removeChild(link);
    }, 2000);
}

  

注意:

1 有的浏览器会有安全验证的问题,可能会连续两次提示打开窗口,这样就需要提供白名单给到相应的浏览器开发者;

2 该方法成功率不是100%,有的手机会完全不支持, 有的浏览器也不支持  经验证opera不支持;

3 具体的market 和 打开app的协议 由产品和客户端提供;

原文地址:https://www.cnblogs.com/xhliang/p/10289666.html