[h5] Scan the QR code to open the app or click to download the function

Background: Sometimes, you will encounter this kind of demand, which is to scan the QR code to open the app. If the user does not have this app, it will prompt it to jump; or, the user installs it for the first time, and jumps to the app store by scanning the QR code, or Download the apk directly.
    It is impossible to call the app directly from the webpage, and some configuration must be done on the native side first. Moreover, the calling methods of Android and Apple are different.

1. Method 1, direct and unified jump to the application market

    On the h5 page, regardless of whether the user has installed the app or not, it will directly jump to the app store, allowing the user to open the app from the app store. This method is relatively simple and direct, and WeChat scanning does not require special processing.
    Idea : First, directly determine whether the device is on the android side or the ios side, and then assign the corresponding app store download link on the click button. When opening the h5 page on WeChat, there is no need to do additional processing. Before the jump, the system will pop up a dialog box by default to ask whether to jump.
insert image description hereinsert image description here
Implementation:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title></title>
        <style type="text/css">
            body{
    
    
                padding-top: 30px;
            }
            .open-app {
    
    
                margin: 30px;
                border-radius: 5px;
                padding: 10px 20px;
                border: 1px solid #ccc;
            }
        </style>
        <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>

        <a class="open-app">click me to store</a>
        
        <script type="text/javascript">

            var iosLinkUrl = "http://apps.apple.com/cn/app/id387682726" // 淘宝 app store 下载地址
            var androidLinkurl = "https://a.app.qq.com/o/simple.jsp?pkgname=com.lucky.luckyclient" //(找不到淘宝应用宝地址,这里以lucky coffee为例)

            var u = navigator.userAgent, isAndroid, isIOS

            window.onload = function() {
    
    
                init()
            }

            function init() {
    
    
                isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端
                isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

                var link = isIOS ? iosLinkUrl : androidLinkurl

                $('a').attr('href', link)
            }
            
        </script>
    </body>
</html>

2. Method 2

    On the h5 page, the user clicks the button to open the app. If the app is already installed on the user's mobile phone, the app will be opened directly. Otherwise, the user will be directed to the application market or download the apk. This kind of operation has a better experience and is convenient for users to operate and use. Moreover, in the case of business needs, you can jump to the specified page of the app and pass parameters.
    Idea : To wake up the app on the h5 page, you need to use the scheme protocol (provided by the app-side partner), but the scheme protocol does not work in the WeChat browser, and sometimes when you open some operations on WeChat that need to jump to the app , will be prompted to open on the browser is the reason.
    Therefore, it is necessary to first judge whether it is a WeChat browser. If it is a WeChat browser, it will prompt to open the browser.

Implementation:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title></title>
        <style type="text/css">
            body{
    
    
                padding-top: 30px;
            }
            .open-app {
    
    
                margin: 30px;
                border-radius: 5px;
                padding: 10px 20px;
                border: 1px solid #ccc;
            }
        </style>
        <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>
        
        <a class="open-app">click me to app</a>
        
        <script type="text/javascript">

            $('a').click(function() {
    
    
                var u = navigator.userAgent;
                var isWeixin = u.toLowerCase().indexOf('micromessenger') !== -1; // 微信内
                var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端
                var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

                // 微信内
                if(isWeixin) {
    
    
                    alert('请在浏览器上打开')
                } else {
    
    
                    //android端
                    if (isAndroid) {
    
    
                        //安卓app的scheme协议
                        window.location.href = 'taobao://';
                        setTimeout(function(){
    
    
                            let hidden = window.document.hidden || window.document.mozHidden || window.document.msHidden ||window.document.webkitHidden 
                            if(typeof hidden =="undefined" || hidden ==false){
    
    
                                //应用宝下载地址 (emmm 找不到淘宝应用宝的地址,这里放的是 lucky coffee 地址)
                                window.location.href ="https://a.app.qq.com/o/simple.jsp?pkgname=com.lucky.luckyclient";
                            }
                        }, 2000);
                    }
                    //ios端
                    if (isIOS) {
    
    
                        //ios的scheme协议
                        window.location.href = 'taobao://'
                        setTimeout(function(){
    
    
                            let hidden = window.document.hidden || window.document.mozHidden || window.document.msHidden ||window.document.webkitHidden 
                            if(typeof hidden =="undefined" || hidden ==false){
    
    
                                //App store下载地址
                                window.location.href = "http://itunes.apple.com/app/id387682726";
                            }
                        }, 2000);
                    }
                }
                
            });
        </script>
    </body>
</html>

If the scheme can be detected, jump to the protocol taobao, that is, open the app;
if taobao has not been awakened after 2 seconds, then it is considered that taobao is not installed on the device, that is, jump to the application market.
Here, you can choose to open the window directly to open the link, or you can use iframe框架it to open the link, but ios9 blocks the iframe tag.

With the help of iframe, a page can be opened on the original page:
If you use an iframe, you can realize the download without reopening the page, and it will not have any impact on the layout of the original page.
key code:

var src = 'http://imtt.dd.qq.com/16891/26747DD8B125A8479AD0C9D22CA47BC9.apk?fsname=com.snda.wifilocating_4.2.91_3211.apk&csr=1bbd';
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = "javascript: '<script>location.href=\"" + src + "\"<\/script>'";
document.getElementsByTagName('body')[0].appendChild(iframe);

The action of the form can also make a request:

var src = 'http://imtt.dd.qq.com/16891/26747DD8B125A8479AD0C9D22CA47BC9.apk?fsname=com.snda.wifilocating_4.2.91_3211.apk&csr=1bbd';
var form = document.createElement('form');
form.action = src;
document.getElementsByTagName('body')[0].appendChild(form);
form.submit();

Supplement: Supplementary introduction to scheme
URL Scheme method to evoke Activity or App
URL Scheme is an internal page jump protocol, through which it is more convenient to jump to a certain page of the app.
scheme应用场景:(Currently 1, 2, 5 are used in a wide range of scenarios)

  1. Through the applet, use the scheme protocol to open the native app;
  2. Click the anchor point on the H5 page, and the app will jump to a specific page according to the specific jump path of the anchor point;
  3. The app side receives the push notification bar message sent by the server side, and jumps to the relevant page according to the click jump path of the message;
  4. The app jumps to another app-specified page according to the URL;
  5. Open the native app through the url in the short message.

Attach a detailed introduction to the Scheme protocol (https://segmentfault.com/a/1190000015880556)

3. Specific application examples

First of all, judge whether it is scanned by WeChat, if yes, prompt the browser to open; after accessing through the browser, judge the source of the device, if it is android, open a new page through iframe, and download the apk; if it is ios, pass location.href opens a new page and jumps to the app store.
The relevant pictures are as follows:
insert image description hereinsert image description hereinsert image description hereinsert image description here
specific implementation:

<!DOCTYPE html>
<html style="font-size: 80.5%;">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta content="no" name="apple-mobile-web-app-capable">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <meta content="telephone=no" name="format-detection">
    <title>下载 - 智能摄像机</title>
    <link rel="stylesheet" type="text/css" href="http://publicfiles.xxx.com/yi_files/all.min.dc422677.css" />
    <script>
    var _hmt = _hmt || [];
    (function() {
      
      
        var hm = document.createElement("script");
        hm.src = "//hm.baidu.com/hm.js?c80f110b564dd5a35f5c9d47bfe0520b";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
    </script>
    <style>
    .a_down{
      
      
        display: block;
    max-width: 65%;
    margin: 2rem auto .5rem;
    font-size: 2.4rem;
    line-height: 2.4rem;
    border: 1px solid #E73861;
    color: #E73861;
    padding: 1rem 0;
    border-radius: .5rem;
    text-align: center;
    }
    #tips{
      
      
        display: none;
        color:#ccc;
        text-align: center;
    }
    </style>
</head>

<body style="background: #ffffff; width:100%;height:100%;">
    <div class="wechat">
        <img class="fc" src="http://publicfiles.xxx.com/yi_files/wechat-notice.png" />
    </div>
    <div id="layout">
        <h2 class="t_title" style="font-family: 'FZLTXHK','Microsoft Yahei';font-weight: initial;color:#00BAAD;font-size: 2.2rem;">智能摄像机</h2>
        <h4 class="t_des" style="font-family: 'FZLTXHK','Microsoft Yahei';color:#4C4C4C;font-weight: 200;">会看会听会思考 引领智能新生活</h4>
         <img style="margin: 3rem auto;max-width: 100%;margin-left:-3%;" src="http://publicfiles.xxx.com/yi_files/yi_02_3.png" />
        <a class="a_down" style=" background-color: #00BAAD; margin-top: -10%;border: 1px solid #00BAAD;color: #00BAAD; font-size: 1.4rem;
line-height: 1.4rem; border-radius: 100px;max-width: 80%;" href="javascript:;"><font style="color:#ffffff">智能下载</font></a>
        <p id="tips"  >正在下载,请稍等!</p>
    </div>
    <script>
    (function(i, s, o, g, r, a, m) {
      
      
        i['GoogleAnalyticsObject'] = r;
        i[r] = i[r] || function() {
      
      
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date();
        a = s.createElement(o),
            m = s.getElementsByTagName(o)[0];
        a.async = 1;
        a.src = g;
        m.parentNode.insertBefore(a, m)
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

    ga('create', 'UA-60717157-3', 'auto');
    ga('send', 'pageview');
    </script>
    <script type="text/javascript" src="http://publicfiles.xxx.com/yi_files/zepto.min.1abd55c5.js"></script>
  <script type="text/javascript" src="assets/js/cam.min.5ab037100.js"></script>
</body>
</html>

Among them, the cam.min.5ab037100.js file is the core code to realize the jump , as follows:

/*
 * 智能机浏览器版本信息:
 *
 */
var browser = {
    
    
    versions: function() {
    
    
        var u = navigator.userAgent,
            app = navigator.appVersion;
        return {
    
     //移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
            weixin: u.indexOf('MicroMessenger') > -1,
			weibo: u.indexOf('weibo') > -1
        };
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
}

if (browser.versions.android) {
    
    
    console.log('增加按钮');
}
if (browser.versions.weixin || browser.versions.weibo) {
    
    
    $('.wechat').addClass('wechat_active');
}
if (!browser.versions.ios) {
    
    
    $('.a_down_url').addClass('android_active');
}
function uuid(){
    
    
	var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
    
    
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; 
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); 
                                                            
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
}
function getCookie(name)
{
    
    
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
function setCookie(name,value)
{
    
    
var Days = 30;
var exp = new Date();
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
$('.a_down').on('click', function() {
    
    
    console.log('下载');
    try {
    
    
        $('#tips').css("display:block")
    } catch (e) {
    
    };
    
	var uuids = getCookie('cid');
	if(null!=uuids && uuids!=""){
    
    
		uuids = uuids;
	}else{
    
    
		uuids =  uuid();
		setCookie('cid',uuids);
	}
	var datelong = new Date().getTime();
    if (browser.versions.android) {
    
    
		$.ajax({
    
    
			url:'https://log.xxx.com/info.gif?cid='+uuids+'&p=android&data={"data":[{"t":"e","c":"AppInsDownload","ts":'+datelong+',"result":"true"}]}',
			type:'get',
			success:function(data){
    
    
				 console.log('成功:'+data);
			}
		})
        try {
    
    
            ga('send', 'event', '家庭相机客户端下载', 'click', '家庭相机客户端下载_Android', 1);
        } catch (e) {
    
    };
        try {
    
    
            _hmt.push(['_trackEvent', '家庭相机客户端下载', 'click', '家庭相机客户端下载_Android', '1']);
        } catch (e) {
    
    }

        var startTime,
            endTime;
        setTimeout(function() {
    
    

            var d = navigator.userAgent.match(/Chrome\/(\d+)/);

            try {
    
    
                startTime = (new Date()).getTime()
                var iframe = document.createElement("iframe");
                iframe.style.border = "none";
                iframe.style.width = "1px";
                iframe.style.height = "1px";
                iframe.src = 'https://publicfiles.xxx.com/app/yicamera_china_release.apk' //'market://details?id=com.ants360.yicamera'; 安卓下载apk地址
                document.body.appendChild(iframe);
                // endTime = (new Date()).getTime();
            } catch (e) {
    
    

            }
    
        }, 0)

    } else if (browser.versions.ios) {
    
    
		$.ajax({
    
    
			url:'https://log.xxx.com/info.gif?cid='+uuids+'&p=ios&data={"data":[{"t":"e","c":"AppInsDownload","ts":'+datelong+',"result":"true"}]}',
			type:'get',
			success:function(data){
    
    
				 console.log('成功:'+data);
			}
		})
        try {
    
    
            ga('send', 'event', '家庭相机客户端下载', 'click', '家庭相机客户端下载_iOS', 1);
        } catch (e) {
    
    };
        try {
    
    
            _hmt.push(['_trackEvent', '家庭相机客户端下载', 'click', '家庭相机客户端下载_iOS', '1']);
        } catch (e) {
    
    }

        setTimeout(function() {
    
    
            location.href = 'https://itunes.apple.com/cn/app/xxx-zhi-neng-she-xiang-ji/id931168730?l=zh&ls=1&mt=8';  //ios地址
        }, 250)
    } else {
    
    
		$.ajax({
    
    
			url:'https://log.xxx.com/info.gif?cid='+uuids+'&p=android&data={"data":[{"t":"e","c":"AppInsDownload","ts":'+datelong+',"result":"true"}]}',
			type:'get',
			success:function(data){
    
    
				 console.log('成功:'+data);
			}
		})
        try {
    
    
            ga('send', 'event', '家庭相机客户端下载', 'click', '家庭相机客户端下载_其他', 1);
        } catch (e) {
    
    };
        try {
    
    
            _hmt.push(['_trackEvent', '家庭相机客户端下载', 'click', '家庭相机客户端下载_其他', '1']);
        } catch (e) {
    
    }
        setTimeout(function() {
    
    
            location.href = 'http://app.mi.com/detail/xxx';  //小米应用商店
        }, 250)
    }

})

$('.a_down_url').on('click', function() {
    
    
    try {
    
    
        ga('send', 'event', '家庭相机客户端下载', 'click', '家庭相机客户端下载_Android_APK_附加URL', 1);
    } catch (e) {
    
    };
    try {
    
    
        _hmt.push(['_trackEvent', '家庭相机客户端下载', 'click', '家庭相机客户端下载_Android_APK_附加URL', '1']);
    } catch (e) {
    
    }
    setTimeout(function() {
    
    
        location.href = 'http://app.mi.com/detail/xxx'; //小米应用商店
    }, 250)
})
console.log(1024)

Reference blog:

The H5 page evokes the specified app or jumps to the application market (scan the QR code to download the APP directly) https://blog.csdn.net/weixin_43085797/article/details/105137059
The H5 page realizes three steps of downloading files (apk, txt, etc.) Two ways https://blog.csdn.net/weixin_34221112/article/details/88768839
h5 Scan the QR code to open the app and click to download the function to realize the
use of https://www.cnblogs.com/sxz2008/p/8245431.html Scan QR code to open app http://www.javashuo.com/article/p-oiyumdpk-bm.html
h5 Scan QR code to open app and click to download http://www.javashuo.com/article/ p-twxyspeb-z.html
Scheme protocol details https://segmentfault.com/a/1190000015880556

Guess you like

Origin blog.csdn.net/qq_26780317/article/details/127634025