前段时间遇到一个小需求:要求在分享出来的h5页面中,有一个当即打开的按钮,若是本地安装了咱们的app,那么点击就直接唤起本地app,若是没有安装,则跳转到下载。javascript
由于历来没有作过这个需求,所以这注定是一个苦逼的调研过程。php
咱们最开始就面临2个问题:一是如何唤起本地app,二是如何判断浏览器是否安装了对应app。css
首先,想要实现这个需求,确定是必需要客户端同窗的配合才行,所以咱们不用知道全部的实现细节,咱们从前端角度思考看这个问题,须要知道的一点是,ios与Android都支持一种叫作schema协议的连接。好比网易新闻客户端的协议为html
newsapp://xxxxx
固然,这个协议不须要咱们前端去实现,咱们只须要将协议放在a标签的href属性里,或者使用location.href与iframe来实现激活这个连接。而location.href与iframe是解决这个需求的关键。前端
在ios中,还支持经过smart app banner
来唤起app,即经过一个meta标签,在标签里带上app的信息,和打开后的行为,代码形如java
<meta name="apple-itunes-app" content="app-id=1023600494, app-argument=tigerbrokersusstock://com.tigerbrokers.usstock/post?postId=7125" />
咱们还须要知道的一点是,微信里屏蔽了schema协议。除非你是微信的合做伙伴之类的,他们专门给你配置进白名单。不然咱们就没办法经过这个协议在微信中直接唤起app。android
所以咱们会判断页面场景是否在微信中,若是在微信中,则会提示用户在浏览器中打开。ios
很无奈的是,在浏览器中没法明确的判断本地是否安装了app。所以咱们必须采起一些取巧的思路来解决这个问题。web
咱们可以很容易想到,采用设置一个延迟定时器setTimeout的方式,第一时间尝试唤起app,若是200ms没有唤起成功,则默认本地没有安装app,200ms之后,将会触发下载行为。json
结合这个思路,咱们来全局考虑一下这个需求应该采用什么样的方案来实现它。
使用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