浏览器中唤起native app || 跳转到运用商城下载

前段时候碰到一个小需求:要求在分享出来的h5页面中,有一个马上翻开的按钮,假如当地装置了我们的app,那末点击就直接唤起当地app,假如没有装置,则跳转到下载。

因为从来没有做过这个需求,因而这注定是一个苦逼的调研历程。

我们最最先就面临2个题目:一是怎样唤起当地app,二是怎样推断阅读器是不是装置了对应app。

怎样唤起当地app

起首,想要完成这个需求,肯定是必需要客户端同砚的合营才行,因而我们不必晓得一切的完成细节,我们从前端角度思索看这个题目,须要晓得的一点是,ios与Android都支撑一种叫做schema协定的链接。比方网易消息客户端的协定为

newsapp://xxxxx

固然,这个协定不须要我们前端去完成,我们只须要将协定放在a标签的href属性里,或许运用location.href与iframe来完成激活这个链接。而location.href与iframe是处置惩罚这个需求的症结。

在ios中,还支撑经由过程smart app banner来唤起app,即经由过程一个meta标签,在标签里带上app的信息,和翻开后的行动,代码形如

<meta name="apple-itunes-app" content="app-id=1023600494, app-argument=tigerbrokersusstock://com.tigerbrokers.usstock/post?postId=7125" />

我们还须要晓得的一点是,微信里屏障了schema协定。除非你是微信的合作伙伴之类的,他们特地给你设置进白名单。不然我们就没办法经由过程这个协定在微信中直接唤起app。

因而我们会推断页面场景是不是在微信中,假如在微信中,则会提醒用户在阅读器中翻开。

怎样推断当地是不是装置了app

很没法的是,在阅读器中没法邃晓的推断当地是不是装置了app。因而我们必需采纳一些取巧的思绪来处置惩罚这个题目。

我们能够很轻易想到,采纳设置一个耽误定时器setTimeout的体式格局,第一时候尝试唤起app,假如200ms没有唤起胜利,则默许当地没有装置app,200ms今后,将会触发下载行动。

连系这个思绪,我们来全局考虑一下这个需求应当采纳什么样的计划来完成它。

运用location.href的同砚可能会面临一个担心,在有的阅读器中,当我们尝试激活schema link的时刻,若当地没有装置app,则会跳转到一个阅读器默许的毛病页面去了。因而大多数人采纳的处置惩罚计划都是运用iframe

测试了很多阅读器,没有发明过这类状况

厥后视察了网易消息,本日头条,YY等的完成计划,发明人人都采纳的是iframe来完成。好吧,面临这类状况,只能屈就。

整顿一下现在的思绪,获得下面的处置惩罚计划

var url = {
  open: 'app://xxxxx',
  down: 'xxxxxxxx'
};
var iframe = document.createElement('iframe');
var body = document.body;
iframe.style.cssText='display:none;width=0;height=0';
var timer = null;

// 马上翻开的按钮
var openapp = document.getElementById('openapp');
openapp.addEventListener('click', function() {
  if(/MicroMessenger/gi.test(navigator.userAgent) {
    // 指导用户在阅读器中翻开
  }) else{
    body.appendChild(iframe);
    iframe.src = url.open;
    timer = setTimeout(function() {
      wondow.location.href = url.down;
    }, 500);
  }
}, false)

主意很优美,实际很严酷。一测试,就发明简朴的如许完成有很多的题目。

第一个题目在于,当页面胜利唤起app以后,我们再切换返来阅读器,发明跳转到了下载页面。

为了处置惩罚这个题目,发明各个公司都进行了差别体式格局的尝试。

也是历经的很多熬煎,发明了几个比较有效的事宜。

pageshow: 页面显现时触发,在load事宜以后触发。须要将该事宜绑定到window上才会触发

pagehide: 页面隐蔽时触发

visibilitychange: 页面隐蔽没有在当前显现时触发,比方切换tab,也会触发该事宜

document.hidden 当页面隐蔽时,该值为true,显现时为false

因为各个阅读器的支撑状况差别,我们须要将这些事宜都给绑定上,纵然如许,也不一定能够保证一切的阅读器都能够处置惩罚掉这个小题目,着实没办法的事变就不管了。

因而须要扩大一下上面的计划,当当地app被唤起,则页面会隐蔽掉,就会触发pagehide与visibilitychange事宜

$(document).on('visibilitychange webkitvisibilitychange', function() {
    var tag = document.hidden || document.webkitHidden;
    if (tag) {
        clearTimeout(timer);
    }
})

$(window).on('pagehide', function() {
    clearTimeout(timer);
})

而别的一个题目就是IOS9+下面的题目了。ios9的Safari,基础不支撑经由过程iframe跳转到其他页面去。也就是说,在safari下,我的团体计划被通盘反对!

因而我就只能尝试运用location.href的体式格局,这个体式格局能够唤起app,然则有一个坑爹的题目,运用schema协定唤起app会有弹窗而不会直接跳转去app!甚至当当地没有app时,会被推断为链接无效,然后另有一个弹窗。

这个弹窗会形成什么题目呢?假如用户不点确认按钮,依据上面的逻辑,这个时刻就会发明页面会自动跳转到下载去了。而且无效的弹窗提醒在用户体验上是不允许涌现的。

好吧,继承扒他人的代码,看看他人是怎样完成的。然后我又去观赏了其他公司的完成效果,发明网易消息,本日头条都能够在ios直接从微信中唤起app。真是奇异了,然则本日头条在Android版微信上也没办法直接唤起的,他们在Android上都是直接到腾讯运用宝的下载里去。所以按原理来讲这不是添加了白名单。

为了找到这个题目的处置惩罚计划,我在网易消息的页面中扒出了他们的代码,并整顿以下,添加了部份解释


window.NRUM = window.NRUM || {};
window.NRUM.config = {
    key:'27e86c0843344caca7ba9ea652d7948d',
    clientStart: +new Date()
};
(function() {
    var n = document.getElementsByTagName('script')[0],
        s = document.createElement('script');

    s.type = 'text/javascript';
    s.async = true;
    s.src = '//nos.netease.com/apmsdk/napm-web-min-1.1.3.js';
    n.parentNode.insertBefore(s, n);
})();


;
(function(window,doc){

    // http://apm.netease.com/manual?api=web
    NRUM.mark && NRUM.mark('pageload', true)

    var list = []
    var config = null

    // jsonp
    function jsonp(a, b, c) {
        var d;
        d = document.createElement('script');
        d.src = a;
        c && (d.charset = c);
        d.onload = function() {
            this.onload = this.onerror = null;
            this.parentNode.removeChild(this);
            b && b(!0);
        };
        d.onerror = function() {
            this.onload = this.onerror = null;
            this.parentNode.removeChild(this);
            b && b(!1);
        };
        document.head.appendChild(d);
    };


    function localParam(search,hash){
        search = search || window.location.search;
        hash = hash || window.location.hash;
        var fn = function(str,reg){
            if(str){
                var data = {};
                str.replace(reg,function( $0, $1, $2, $3 ){
                    data[ $1 ] = $3;
                });
                return data;
            }
        }
        return {search: fn(search,new RegExp( "([^?=&]+)(=([^&]*))?", "g" ))||{},hash: fn(hash,new RegExp( "([^#=&]+)(=([^&]*))?", "g" ))||{}};
    }

    jsonp('http://active.163.com/service/form/v1/5847/view/1047.jsonp')

    window.search = localParam().search
    window._callback = function(data) {
        window._callback = null
        list = data.list
        if(search.s && !!search.s.match(/^wap/i)) {
            config = list.filter(function(item){
                return item.type === 'wap'
            })[0]
            return
        }
        config = list.filter(function(item){
            return item.type === search.s
        })[0]
    }

    var isAndroid = !!navigator.userAgent.match(/android/ig),
        isIos = !!navigator.userAgent.match(/iphone|ipod/ig),
        isIpad = !!navigator.userAgent.match(/ipad/ig),
        isIos9 = !!navigator.userAgent.match(/OS 9/ig),
        isYx = !!navigator.userAgent.match(/MailMaster_Android/i),
        isNewsapp = !!navigator.userAgent.match(/newsapp/i),
        isWeixin = (/MicroMessenger/ig).test(navigator.userAgent),
        isYixin = (/yixin/ig).test(navigator.userAgent),
        isQQ = (/qq/ig).test(navigator.userAgent),
        params = localParam().search,
        url = 'newsapp://',
        iframe = document.getElementById('iframe');

    var isIDevicePhone = (/iphone|ipod/gi).test(navigator.platform);
    var isIDeviceIpad = !isIDevicePhone && (/ipad/gi).test(navigator.platform);
    var isIDevice = isIDevicePhone || isIDeviceIpad;
    var isandroid2_x = !isIDevice && (/android\s?2\./gi).test(navigator.userAgent);
    var isIEMobile = !isIDevice && !isAndroid && (/MSIE/gi).test(navigator.userAgent);
    var android_url = (!isandroid2_x) ? "http://3g.163.com/links/4304" : "http://3g.163.com/links/6264";
    var ios_url = "http://3g.163.com/links/3615";
    var wphone_url = "http://3g.163.com/links/3614";
    var channel = params.s || 'newsapp'

    // 推断在差别环境下app的url
    if(params.docid){
        if(params['boardid'] && params['title']){
            url = url + 'comment/' + params.boardid + '/' + params.docid + '/' + params.title
        }else{
            url = url + 'doc/' + params.docid
        }
    }else if(params.sid){
        url = url + 'topic/' + params.sid
    }else if(params.pid){
        var pid = params.pid.split('_')
        url = url + 'photo/' + pid[0] + '/' + pid[1]
    }else if(params.vid){
        url = url + 'video/' + params.vid
    }else if(params.liveRoomid){
        url = url + 'live/' + params.liveRoomid
    }else if(params.url){
        url = url + 'web/' + decodeURIComponent(params.url)
    }else if(params.expertid){
        url = url + 'expert/' + params.expertid
    }else if(params.subjectid){
        url = url + 'subject/' + params.subjectid
    }else if(params.readerid){
        url = url + 'reader/' + params.readerid
    }else{
        url += 'startup'
    }
    if(url.indexOf('?') >= 0){
        url += '&s=' + (params.s || 'sps')
    }else{
        url += '?s=' + (params.s || 'sps')
    }

    // ios && 易信  用iframe 翻开
    if((isIos||isIpad) && navigator.userAgent.match(/yixin/i)) {
        document.getElementById('iframe').src = url;
    }

    var height = document.documentElement.clientHeight;

    // 通常状况下先尝试运用iframe翻开
    document.getElementById('iframe').src = url;

    // 挪动端阅读器中,将下载页面显现出来
    if(!isWeixin && !isQQ && !isYixin && !isYx){
        document.querySelector('.main-body').style.display = 'block'
        if(isIos9){
            document.querySelector('.main-body').classList.add('showtip')
        }

        setTimeout(function(){
            document.body.scrollTop = 0
        },200)
    }else{
        document.getElementById('guide').style.display = 'block'
    }

    // Forward To Redirect Url
    // Add by zhanzhixiang 12/28/2015
    if (params.redirect) {
        var redirectUrl = decodeURIComponent(params.redirect);
        if ( typeof(URL) === 'function' && new URL(redirectUrl).hostname.search("163.com") !== -1) {
            window.location.href = redirectUrl;
        } else if (redirectUrl.search("163.com") !== -1){
            window.location.href = redirectUrl;
        };
    }

    // Forward To Redirect Url End
    if ((isWeixin || isQQ) && isAndroid) {
        window.location.href = 'http://a.app.qq.com/o/simple.jsp?pkgname=com.netease.newsreader.activity&ckey=CK1331205846719&android_schema=' + url.match(/(.*)\?/)[1]
    }

    if(isIos||isIpad){
        document.getElementById("guide").classList.add('iosguideopen')
    }else if (isAndroid){
        document.getElementById("guide").classList.add('androidguideopen')
    }else{
        // window.location.href = 'http://www.163.com/newsapp'
    }

    document.getElementById('link').addEventListener('click', function(){

        // 统计
        neteaseTracker && neteaseTracker(false,'http://sps.163.com/func/?func=downloadapp&modelid='+modelid+'&spst='+spst+'&spsf&spss=' + channel,'', 'sps' )

        if (config) {
            android_url = config.android
        }
        if (config && config.iOS) {
            ios_url = config.iOS
        }
        if(isWeixin || isQQ){
            return
        }
        var msg = isIDeviceIpad ? "检测到您正在运用iPad, 是不是直接前去AppStore下载?" : "检测到您正在运用iPhone, 是不是直接前去AppStore下载?";
        if (isIDevice){
            window.location = ios_url;
            return;
        }else if(isAndroid){
            // uc阅读器用iframe叫醒
            if(navigator.userAgent.match(/ucbrowser|yixin|MailMaster/i)){
                document.getElementById('iframe').src = url;
            } else {
                window.location.href = url;
            }
            setTimeout(function(){
                if(document.webkitHidden) {
                    return
                }
                if (confirm("检测到您正在运用Android 手机,是不是直接下载顺序装置包?")) {
                    neteaseTracker && neteaseTracker(false,'http://sps.163.com/func/?func=downloadapp_pass&modelid='+modelid+'&spst='+spst+'&spsf&spss=' + channel,'', 'sps' )
                    window.location.href = android_url;
                } else {
                    neteaseTracker && neteaseTracker(false,'http://sps.163.com/func/?func=downloadapp_cancel&modelid='+modelid+'&spst='+spst+'&spsf&spss=' + channel,'', 'sps' )
                }
            },200)
            return;
        }else if(isIEMobile){
            window.location = wphone_url;
            return;
        }else{
            window.open('http://www.163.com/special/00774IQ6/newsapp_download.html');
            return;
        }
    }, false)

    setTimeout(function(){
        if(isIDevice && params.notdownload != 1 && !isNewsapp && !isIos9){
            document.getElementById('link').click()
        }
    }, 1000)

})(window,document);

虽然有一些外部的援用,和一些搞不懂是干什么用的要领和变量,然则基础逻辑照样能够看邃晓。彷佛也没有什么迥殊的处所。研讨了好久,看到了一个jsonp要求很奇异。这是来干吗用的?

因而费尽历尽艰辛,搜刮了很多文章,终究锁定了一个症结的名词 Universal links

假如我早晓得这个名词,那末题目就不会变的那末一筹莫展。所以这个东西是什么呢?

Apple为iOS 9宣布了一个所谓的通用链接的深层链接特征,即Universal links。虽然它并不圆满,然则这一宣布,让数以千计的运用开辟人员倏忽意想到本身的运用体验被突破。

Universal links,一种能够轻易的经由过程传统的HTTP/HTTPS 链接来启动App,运用雷同的网址翻开网站和App。

关于这个题目的发问与universal links的引见 点击这里检察

ios9履行的一个新的协定!

关于本文的这个题目,国内的论坛有许很多多的文章来处置惩罚,然则提到universal links的文章少之又少,而我想吐槽的是,我们的ios开辟也尼玛不晓得这个名词,搞什么鬼。他改变了用户体验的症结在于,微信没有屏障这个协定。因而假如我们的app注册了这个协定,那末我们就能够从微信中直接唤起app。

这个时刻我就发明,上面贴的网易消息代码中的jsonp要求的内容,就是这个协定必需的一个叫做apple-app-site-association的JSON文件

{
   "applinks": {
       "apps": [ ],
       "details": {
           "TEAM-IDENTIFIER.YOUR.BUNDLE.IDENTIFIER": {
               "paths": [
                   "*"
               ]
           }
       }
   }
}

人人能够直接接见这个链接,检察内里的内容

http://active.163.com/service…

至于universal links详细怎样完成,让ios的同砚去搞定吧,这里供应两个参考文章

http://www.cocoachina.com/bbs…

https://blog.branch.io/how-to…

支撑了这个协定以后,我们又能够经由过程iframe来唤起app了,因而基础逻辑就是如许了。

然则!并非就没有坑了。

universal links另有一个大坑,就是假如想要经由过程universal links只在在微信中翻开app,同一个页面我们还得运用差别的两个域名。

这个特征虽然有点坑,然则经由过程这个特征却能够圆满推断当地是不是装置了你们的app。

比方我们一般接见当前页面的域名为A,对应的页面url为A+,而当我们点击按钮,须要翻开app用到的域名为B,,对应的页面url为B+。

A与B都被注册成为了对应app的universal links,A+ 与 B+ 都指向同一个页面。

我们经由过程js推断,假如是经由过程B+接见的该页面,则直接跳去下载app。如许,当我们从A+经由过程点击接见B+时,假如universal links见效而且当地装置了对应的app,app会直接被翻开。假如当地没有装置App,则会直接实行适才B+中跳去下载的设定。

OK,这个题目,险些一切的坑我都在上面说到了,假如想要做好兼容,就是一个针对每一个坑做最优挑选了,这是一个工作量的题目。

不过终究的调研效果是

没有圆满的处置惩罚计划

就算是网易消息,这个按钮在运用历程中也会有一些小bug,没法做到圆满的状况。

因为我们面临很多没办法处置惩罚的题目,比方没法真正意义上的推断当地是不是装置了app,pageshow,pagehide并非一切的阅读器都支撑等。很多其他博客内里,什么盘算时候差等计划,我花了良久的时候去研讨这个计划,效果是,根!本!没!有!用!

老实说,从微信中跳转到外部阅读器,并非一个好的处置惩罚计划,如许会致使很多用户流失,因而人人都在ios上完成了universal links。

网易消息的逻辑是,点击翻开会跳转到一个下载页面,这个下载页面一加载完造诣尝试翻开app,假如翻开了就直接跑到app内里去了,假如没有就在页面上有一个马上下载的按钮,按钮行只要下载处置惩罚。

这个题目就总结到这里,假如人人有更好的计划,迎接与我沟通。

不必折腾universal link了,微信已禁用 ~ 2018-01-08

《浏览器中唤起native app || 跳转到运用商城下载》

    原文作者:九死蚕传人bo
    原文地址: https://segmentfault.com/a/1190000005848133
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞