vue中h5端打开app(判断是安卓还是苹果)
(编辑:jimmy 日期: 2025/10/24 浏览:3 次 )
1.开发环境 vue+vant
2.电脑系统 windows10专业版
3.在h5端开发的过程中,我们经常需要点击一个按钮来判断用户使用安装了app(首先判断是安卓还是苹果,然后判断是否安装了app,如果没有安装则跳转到下载页面,如果安装了则打开)。
4.废话不多说,直接上代码:
<div class="xiding-r" @click="openapp"> Open APP </div>
5.在methods中添加如下代码:
openapp() {
var u = navigator.userAgent,
app = navigator.appVersion;
var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1;
var isIOS = !!u.match(/\(i[^;]+;( U;)"我是安卓");
this.android();
}
if (isIOS) {
// alert("我是苹果");
}
},
android() {
var _clickTime = new Date().getTime();
window.location.href = 'zhihu://'; /***打开app的协议,有安卓同事提供***/
//启动间隔20ms运行的定时器,并检测累计消耗时间是否超过3000ms,超过则结束
var _count = 0, intHandle;
intHandle = setInterval(function () {
_count++;
var elsTime = new Date().getTime() - _clickTime;
if (_count >= 100 || elsTime > 5000) {
console.log(_count)
console.log(elsTime)
clearInterval(intHandle);
//检查app是否打开
if (document.hidden || document.webkitHidden) {
// 打开了
window.location.href = "zhihu://";
// alert('打开了');
window.close();
// return;
} else {
// 没打开
// alert('没打开');
window.location.href = "";//下载链接
}
}
}, 20);
},
5.注意:在这个案例中我是用的知乎的例子:
6.注意
使用Custom URL Scheme的好处就是,你可以在其他程序中通过这个url打开应用程序。如果A应用程序注册了一个 url scheme:myApp,那么就在mobile浏览器中就可以通过<a href ="myApp://">打开你的应用程序。请注意,IOS中如果系统注册了 url schemen且安装了那个应用程序,通过上面那种网页的方式就可以打开应用程序(亲测有效)。注意:IOS中不能注册为http://xxx这样的url scheme,而android是可以的。
下一篇:JavaScript 中的执行上下文和执行栈实例讲解
