需求
判断是否有安装app, 安装了则跳转应用, 没有安装则跳转下载页
参考文章
通过浏览器判断是否安装APP
H5判断是否安装某款app,打开app或跳转到app下载页面
完整代码
<template>
<iframe
:value="iframeSrc"
ref="iframe"
style="display: none; width: 0; height: 0"
></iframe>
<div class="button" @click="openApp">
<span>test</span>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const iframeSrc = ref("");
const iframe = ref(null);
const iframeConfig = {
iosScheme: "com.example.app://",
iosStoreLink: "https://apps.apple.com/app/",
androidScheme: "com.example.app://",
androidStoreLink: "https://play.google.com/store/apps/details?",
fallbackUrl: "https:/www.miti.chat",
};
function openApp() {
const userAgent = navigator.userAgent;
const startTime = new Date().getTime();
console.log(startTime);
console.log(userAgent);
if (/iPhone|iPod|iPad/i.test(userAgent)) {
iframeSrc.value = iframeConfig.iosScheme;
setTimeout(() => {
const endTime = new Date().getTime();
if (endTime - startTime < 2000) {
window.location.href = iframeConfig.iosStoreLink;
}
}, 1000);
} else if (/android/i.test(userAgent)) {
iframeSrc.value = iframeConfig.androidScheme;
setTimeout(() => {
const endTime = new Date().getTime();
if (endTime - startTime < 2000) {
window.location.href = iframeConfig.androidStoreLink;
}
}, 1000);
iframeSrc.value = "";
} else {
window.location.href = iframeConfig.fallbackUrl;
}
console.log(iframeSrc.value);
}
</script>
const CONFIG = {
iosScheme: "com.example.app://", // 替换成你的 iOS 应用 URL
iosDownload: "https://apps.apple.com/app/example-app-id", // 替换成你的 iOS 下载页面 URL
androidScheme: "com.example.app://", // 替换成你的 Android 应用 URL
androidDownload:
"https://play.google.com/store/apps/details?id=com.example.app", // 替换成你的 Android 下载页面 URL
};
function openApp() {
const userAgent = navigator.userAgent;
const iframe: HTMLIFrameElement = document.createElement("iframe");
iframe.style.display = "none"; // 确保 iframe 不会显示在页面上
const startTime = new Date().getTime();
let hasApp = true; // 假设设备上已安装应用
if (/iPhone|iPod|iPad/i.test(userAgent)) {
iframe.src = CONFIG.iosScheme; // 尝试打开 iOS 应用的 URL
setTimeout(() => {
const endTime = new Date().getTime();
if (endTime - startTime < 2000) {
hasApp = false;
window.location.href = CONFIG.iosDownload; // 跳转到 iOS 下载页面的 URL
}
document.body.removeChild(iframe);
}, 1000);
} else if (/android/i.test(userAgent)) {
iframe.src = CONFIG.androidScheme; // 尝试打开 Android 应用的 URL
setTimeout(() => {
const endTime = new Date().getTime();
if (endTime - startTime < 2000) {
hasApp = false;
window.location.href = CONFIG.androidDownload; // 跳转到 Android 下载页面的 URL
}
document.body.removeChild(iframe);
}, 1000);
}
}
export default openApp;