Skip to main content

(Firefox) WebApp自動偵測與安裝腳本

· 3 min read

這陣子在了解如何開發 webapp,其實基本流程很簡單。 要把網頁變成 webapp,最基本的動作就是照著說明寫個 manifest.webapp 檔案,放到網站的根目錄,然後在 web server 的設定加入對應的 MIME type 即可。用 Github Page 放網站的話,最後的 MIME 設定他們都幫我們弄好了。

使用者在電腦上透過 Firefox 安裝 webapp 後,就會多出一個對應的應用程式圖示,開啓這個 WebApp 時不會出現瀏覽器框,感覺就像真的應用程式。在 Android 上透過 Firefox for Android (測試版) 安裝 webapp 後,在桌面上則會多出一個 bookmark 捷徑。

圖:在 Mac 桌面上打開 2 個 webapp,不特別講也分不出來是 Web 還是 App 吧

我在測試的時候,發現寫好了 webapp 之後,使用者連到網頁時並不會自動詢問使用者是否要安裝 webapp。於是寫了以下腳本。

在 Body 標簽中引用以下腳本,即可自動偵測使用者是否可安裝 webapp (現在只有 Firefox Aurora 和 Firefox OS 支援 webapp API)

<script type="text/javascript"> //check if app is installed if( navigator.mozApps != undefined ){var app_stat = navigator.mozApps.getSelf(); app_stat.onsuccess = function() {   if (app_stat.result) {         //instsalled   } else {         // not installed         var manifestUrl = location.href.substring(0, location.href.lastIndexOf('/'))+'/manifest.webapp';         var app_install = navigator.mozApps.install(manifestUrl);   }}; app_stat.onerror = function() {   alert('Error checking installation status: '+ this.error.message); }; } </script> 原始碼包含在 webapplate 專案中。

透過

location.href.substring (0, location.href.lastIndexOf ('/'))+'/manifest.webapp'; 可以自動取得目前的 IP 或網址。