[JavaScript] 網頁開啟 APP - 透過 URL Scheme

URL Scheme 是 APP 的一個功能,可以讓開發者根據路徑 (URL) 啟動 APP。

程式碼

一般來說,只要將網址路徑直接更新成 APP URL Scheme 就能啟動 APP (使用 window.location) ,但是在一些非 Mobile 或特別的瀏覽器的環境下,直接跳轉會到一個無效頁面,這時需要透過 iframe 在網頁背景執行啟動。
此外,針對沒有成功開啟 APP 的例外情況,可以設個計時器 (使用 window.setTimeout) 讓其時間到跳轉到特定網頁 (像是 APP 下載 URL)。目前在一些新版的 Mobile 瀏覽器,會多跳一個是否啟動 APP 的確認視窗,所以可透過 window.onblur 事件來確認。
完整程式碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function openApp(appUrl, webUrl) {
// 避免啟動失敗的計時器
var timer = window.setTimeout(() => {
if (webUrl) {
window.location.href = webUrl;
}
}, 1000);

// 判斷瀏覽器來區分啟動方式
var ifr;
if (navigator.userAgent.match(/(Safari)/i)) {
if (navigator.userAgent.match(/(iPhone|iPad|iPod)/i)) {
window.clearTimeout(timer);
window.location.replace(appUrl);
} else if (navigator.userAgent.match(/Mobile/i)) {
window.clearTimeout(timer);
window.location.replace(appUrl);
} else {
ifr = document.createElement('iframe');

ifr.src = appUrl;
ifr.style.display = 'none';
document.body.appendChild(ifr);
}
} else if (navigator.userAgent.match(/Chrome/i)) {
window.clearTimeout(timer);
window.location.replace(appUrl);
} else {
ifr = document.createElement('iframe');

ifr.src = appUrl;
ifr.style.display = 'none';
document.body.appendChild(ifr);
}

// 用 onblur 來確認有沒有多跳一個是否啟動 APP 的確認視窗
window.onblur = () => {
window.clearTimeout(timer);
if (ifr) {
ifr.remove();
}
window.close();
};

window.setTimeout(() => {
if (ifr) {
ifr.remove();
}
}, 10000);
}

隨著瀏覽器不斷更新,有些方式或許會不適用。

  • 2021/09/07 測試,在常用的 Chrome 與 Safari 上正常。

參考資料