xwartz/xwartz.github.com

在手机浏览器上打开应用

xwartz opened this issue · 1 comments

iOS

Safari

iOS上就是这么的简单, 自带功能,搞定

<meta name="apple-itunes-app" content="app-id=yourappid">
Chrome
//有就打开,没有就跳转到iTunes, 这里的chrome还算乖的,不打开空白页..
window.location = appUrl;
window.setTimeout(function() {
      window.location = apkUrl
}, 250);

Android

Chrome 25- 或者其他浏览器

使用iframe来打开,没有安装就跳市场或下载

var ifr = document.createElement("iframe");
      ifr.style.display = 'none';
      ifr.src = appUrl;
      document.body.appendChild(ifr);
      var d = new Date;
      window.setTimeout(function() {
            if(600 > new Date - d) {
                window.location = apkUrl;
            }
}, 400);
Chrome 25+

这个比较坑,由于Google更改了机制,Android Intents with Chrome, 不能再使用iframe打开应用了。
so,只能使用Intent.

intent:
   HOST/URI-path // Optional host 
   #Intent; 
      package=[string]; 
      action=[string]; 
      category=[string]; 
      component=[string]; 
      scheme=[string]; 
   end; 

所以最终代码就是这样子的。

// appurl: URL scheme
// apkurl: app download url
//chrome25Url: Intent url
var tryOpenApp = function (appUrl, apkUrl, chrome25Url) {

    if (Platform.isAndroid) {
        var v = navigator.userAgent.match(/Chrome\/(\d+)/);
        if (25 <= (v && v[1])) {
            window.location = chrome25Url;
        } else {
            var ifr = document.createElement("iframe");
            ifr.style.display = 'none';
            ifr.src = appUrl;
            document.body.appendChild(ifr);
            var d = new Date;
            window.setTimeout(function() {
                if(600 > new Date - d) {
                    window.location = apkUrl;
                }
            }, 400);
        }
    } else {
        window.location = appUrl;
        window.setTimeout(function() {
            window.location = apkUrl
        }, 250);
    }
}

Reference:

Android Intents with Chrome
URL schemes for iOS and Android (2/2)