作成日:2024-04-19, 更新日:2024-04-19
基本
- アプリ側からiOS、アンドロイド、インストールされていない場合のURLなどを教えてもらう
- javascriptでユーザーエージェントを使って処理分岐
- アプリが開かないときはストアかダウンロードページへ飛ばす
javascript
class toAppUtility {
constructor(init_prms) {
// アプリ起動用
this.app_ios = 'iosアプリのURLスキーマ://xxxx';
this.app_android = 'androidアプリのURLスキーマ://xxxx';
// ストア用
this.url_ios = 'https://apps.apple.com/app/[your-app-id]';
this.url_android = 'https://play.google.com/store/apps/details?id=[your-package-name]';
// アプリが起動しない、ストアも起動しない場合の最終的なURL
this.url_fallback = 'https://アプリのダウンロードページまたはストアのURL';
// アプリが起動したか?
this.appLaunched = false;
}
getDeviceType() {
let userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
return 'ios';
}
else if (/android/i.test(userAgent)) {
return 'android';
}
else {
return 'other';
}
}
delay(duration) {
return new Promise(resolve => setTimeout(resolve, duration));
}
setupFocusEvent() {
window.addEventListener('blur', () => {
this.appLaunched = true;
});
}
async redirectToApp() {
this.setupFocusEvent();
let deviceType = this.getDeviceType();
if (deviceType === 'ios' || deviceType === 'android') {
let appSchema = deviceType === 'ios' ? this.app_ios : this.app_android;
window.location = appSchema; // アプリ起動
await this.delay(2000); // 初回のタイムアウト(2秒)
if (!this.appLaunched) { // アプリ起動失敗
let storeUrl = deviceType === 'ios' ? this.url_ios : this.url_android;
window.location = storeUrl; // ストアへのリダイレクト
await this.delay(3000); // ストアのタイムアウト(3秒)
if (!this.appLaunched) { // ストア起動失敗
window.location = this.url_fallback; // フォールバックURLへのリダイレクト
}
}
}
else { // PCまたはその他のデバイス
window.location = this.url_fallback;
}
}
}
let toApp_util = new toAppUtility();
toApp_util.redirectToApp();