瀏覽器中喚起Native App
前段時間遇到一個小需求:要求在分享出來的h5頁面中,有一個立即打開的按鈕,如果本地安裝了我們的app,那么點擊就直接喚起本地app,如果沒有安裝,則跳轉(zhuǎn)到下載。
因為從來沒有做過這個需求,因此這注定是一個苦逼的調(diào)研過程。
我們最開始就面臨2個問題:一是如何喚起本地app,二是如何判斷瀏覽器是否安裝了對應app。
如何喚起本地app
首先,想要實現(xiàn)這個需求,肯定是必須要客戶端同學的配合才行,因此我們不用知道所有的實現(xiàn)細節(jié),我們從前端角度思考看這個問題,需要知道的一點是,ios與Android都支持一種叫做schema協(xié)議的鏈接。比如網(wǎng)易新聞客戶端的協(xié)議為
- newsapp://xxxxx
 
當然,這個協(xié)議不需要我們前端去實現(xiàn),我們只需要將協(xié)議放在a標簽的href屬性里,或者使用location.href與iframe來實現(xiàn)激活這個鏈接。而location.href與iframe是解決這個需求的關(guān)鍵。
在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協(xié)議。除非你是微信的合作伙伴之類的,他們專門給你配置進白名單。否則我們就沒辦法通過這個協(xié)議在微信中直接喚起app。
因此我們會判斷頁面場景是否在微信中,如果在微信中,則會提示用戶在瀏覽器中打開。
如何判斷本地是否安裝了app
很無奈的是,在瀏覽器中無法明確的判斷本地是否安裝了app。因此我們必須采取一些取巧的思路來解決這個問題。
我們能夠很容易想到,采用設(shè)置一個延遲定時器setTimeout的方式,***時間嘗試喚起app,如果200ms沒有喚起成功,則默認本地沒有安裝app,200ms以后,將會觸發(fā)下載行為。
結(jié)合這個思路,我們來全局考慮一下這個需求應該采用什么樣的方案來實現(xiàn)它。
使用location.href的同學可能會面臨一個擔憂,在有的瀏覽器中,當我們嘗試激活schema link的時候,若本地沒有安裝app,則會跳轉(zhuǎn)到一個瀏覽器默認的錯誤頁面去了。因此大多數(shù)人采用的解決方案都是使用iframe
測試了很多瀏覽器,沒有發(fā)現(xiàn)過這種情況
后來觀察了網(wǎng)易新聞,今日頭條,YY等的實現(xiàn)方案,發(fā)現(xiàn)大家都采用的是iframe來實現(xiàn)。好吧,面對這種情況,只能屈服。
整理一下目前的思路,得到下面的解決方案
- 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)
 
想法很美好,現(xiàn)實很殘酷。一測試,就發(fā)現(xiàn)簡單的這樣實現(xiàn)有許多的問題。
***個問題在于,當頁面成功喚起app之后,我們再切換回來瀏覽器,發(fā)現(xiàn)跳轉(zhuǎn)到了下載頁面。
為了解決這個問題,發(fā)現(xiàn)各個公司都進行了不同方式的嘗試。
也是歷經(jīng)的很多折磨,發(fā)現(xiàn)了幾個比較有用的事件。
pageshow: 頁面顯示時觸發(fā),在load事件之后觸發(fā)。需要將該事件綁定到window上才會觸發(fā)
pagehide: 頁面隱藏時觸發(fā)
visibilitychange: 頁面隱藏沒有在當前顯示時觸發(fā),比如切換tab,也會觸發(fā)該事件
document.hidden 當頁面隱藏時,該值為true,顯示時為false
由于各個瀏覽器的支持情況不同,我們需要將這些事件都給綁定上,即使這樣,也不一定能夠保證所有的瀏覽器都能夠解決掉這個小問題,實在沒辦法的事情就不管了。
因此需要擴充一下上面的方案,當本地app被喚起,則頁面會隱藏掉,就會觸發(fā)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跳轉(zhuǎn)到其他頁面去。也就是說,在safari下,我的整體方案被全盤否決!
于是我就只能嘗試使用location.href的方式,這個方式能夠喚起app,但是有一個坑爹的問題,使用schema協(xié)議喚起app會有彈窗而不會直接跳轉(zhuǎn)去app!甚至當本地沒有app時,會被判斷為鏈接無效,然后還有一個彈窗。
這個彈窗會造成什么問題呢?如果用戶不點確認按鈕,根據(jù)上面的邏輯,這個時候就會發(fā)現(xiàn)頁面會自動跳轉(zhuǎn)到下載去了。而且無效的彈窗提示在用戶體驗上是不允許出現(xiàn)的。
好吧,繼續(xù)扒別人的代碼,看看別人是如何實現(xiàn)的。然后我又去觀摩了其他公司的實現(xiàn)結(jié)果,發(fā)現(xiàn)網(wǎng)易新聞,今日頭條都可以在ios直接從微信中喚起app。真是神奇了,可是今日頭條在Android版微信上也沒辦法直接喚起的,他們在Android上都是直接到騰訊應用寶的下載里去。所以按道理來說這不是添加了白名單。
為了找到這個問題的解決方案,我在網(wǎng)易新聞的頁面中扒出了他們的代碼,并整理如下,添加了部分注釋
- 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'
 - // 判斷在不同環(huán)境下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(){
 - // 統(tǒng)計
 - 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請求很奇特。這是來干嘛用的?
于是費盡千辛萬苦,搜索了很多文章,最終鎖定了一個關(guān)鍵的名詞 Universal links。
如果我早知道這個名詞,那么問題就不會變的那么束手無策。所以這個東西是什么呢?
Apple為iOS 9發(fā)布了一個所謂的通用鏈接的深層鏈接特性,即Universal links。雖然它并不***,但是這一發(fā)布,讓數(shù)以千計的應用開發(fā)人員突然意識到自己的應用體驗被打破。
Universal links,一種能夠方便的通過傳統(tǒng)的HTTP/HTTPS 鏈接來啟動App,使用相同的網(wǎng)址打開網(wǎng)站和App。
關(guān)于這個問題的提問與universal links的介紹(http://stackoverflow.com/questions/31891777/ios-9-safari-iframe-src-with-custom-url-scheme-not-working)
ios9推行的一個新的協(xié)議!
關(guān)于本文的這個問題,國內(nèi)的論壇有許許多多的文章來解決,但是提到universal links的文章少之又少,而我想吐槽的是,我們的ios開發(fā)也尼瑪不知道這個名詞,搞什么鬼。他改變了用戶體驗的關(guān)鍵在于,微信沒有屏蔽這個協(xié)議。因此如果我們的app注冊了這個協(xié)議,那么我們就能夠從微信中直接喚起app。
這個時候我就發(fā)現(xiàn),上面貼的網(wǎng)易新聞代碼中的jsonp請求的內(nèi)容,就是這個協(xié)議必須的一個叫做apple-app-site-association的JSON文件
- {
 - "applinks": {
 - "apps": [ ],
 - "details": {
 - "TEAM-IDENTIFIER.YOUR.BUNDLE.IDENTIFIER": {
 - "paths": [
 - "*"
 - ]
 - }
 - }
 - }
 - }
 
大家可以直接訪問這個鏈接,查看里面的內(nèi)容
http://active.163.com/service…
至于universal links具體如何實現(xiàn),讓ios的同學去搞定吧,這里提供兩個參考文章
http://www.cocoachina.com/bbs…
https://blog.branch.io/how-to…
支持了這個協(xié)議之后,我們又可以通過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,則會直接執(zhí)行剛才B+中跳去下載的設(shè)定。
OK,這個問題,幾乎所有的坑我都在上面說到了,如果想要做好兼容,就是一個針對每個坑做***選擇了,這是一個工作量的問題。
不過最終的調(diào)研結(jié)果是
沒有***的解決方案
就算是網(wǎng)易新聞,這個按鈕在使用過程中也會有一些小bug,無法做到***的狀態(tài)。
因為我們面臨許多沒辦法解決的問題,比如無法真正意義上的判斷本地是否安裝了app,pageshow,pagehide并不是所有的瀏覽器都支持等。很多其他博客里面,什么計算時間差等方案,我花了很久的時間去研究這個方案,結(jié)果是,根!本!沒!有!用!
老實說,從微信中跳轉(zhuǎn)到外部瀏覽器,并不是一個好的解決方案,這樣會導致很多用戶流失,因此大家都在ios上實現(xiàn)了universal links。
網(wǎng)易新聞的邏輯是,點擊打開會跳轉(zhuǎn)到一個下載頁面,這個下載頁面一加載完成就嘗試打開app,如果打開了就直接跑到app里面去了,如果沒有就在頁面上有一個立即下載的按鈕,按鈕行只有下載處理。
這個問題就總結(jié)到這里,如果大家有更好的方案,歡迎與我溝通。
















 
 
 
 
 
 
 