---
title: "单击链接打开APP，或自动跳转下载页"
author: "tipx"
date: "2015-02-26T15:51:34Z"
tags: []
categories: ["Web前端"]
slug: "app"
draft: false
lastmod: "2015-02-26T15:56:56Z"
id: 2186943
url: "https://tipx.iteye.com/blog/2186943"
---

手机等移动终端上的页面中，访问链接（使用APP的自定义协议）自动打开相应的APP，若未安装该APP，则重定向至下载页面或下载链接。

网上找的不够完整，参考了下淘宝，立贴备忘。


```java

<a href="javascript:;" id="opener" >打开客户端</a>
<script type="text/javascript">
    var timer, ifr;
    document.getElementById('openApp').onclick = function(e){
        // 通过iframe的方式试图打开APP，如果能正常打开，会直接切换到APP，并自动阻止a标签的默认行为
        ifr = document.createElement('iframe');
        ifr.src = 'myapp://xxxx';  //APP定义的打开协议
        ifr.style.display = 'none';
        document.body.appendChild(ifr);
        
        //1秒内未打开APP，则跳转下载等。
        timer = window.setTimeout(function(){
            location.href = "http://下载链接/..."; 
        }, 1000);
    }

    //摘自“淘宝”，打开APP后，自动移除下载跳转
    window.onblur = function(){
        if(timer){
            clearTimeout(timer);
            timer = null;
        }

        if(ifr){
            document.body.removeChild(ifr);
        }
    }
</script>

```


大部分代码摘自http://blog.woodbunny.com/tb.php?sc=2aab02&id=140