PWA(Progressive Web App)入门系列:安装 Web 应用
前言
在傳統的 Web 應用中,通常只能通過在瀏覽器的地址欄里輸入相應的網址才能進行訪問,或者把網頁地址創建到桌面上通過點擊,然后在瀏覽器里打開。
傳統模式下,圖標、啟動畫面、主題色、視圖模式、屏幕方向等等都無法去自定義和控制。
而目前可以通過 PWA 標準中的特性來完成上面這些功能,使得訪問 Web 應用的路徑更短、曝光性更大,下面說一下這一塊。
安裝
安裝 Web 應用需要一些前期準備。
安裝條件
首先需要在網站下建立 manifest.json 文件,并在頁面中引入:
<link rel="manifest" href="./manifest.json" />且 manifest.json 文件中必須配置如下字段:
{"short_name": "短應用名","name": "長應用名","icons": [{"src": "icons/192.png","sizes": "144x144","type": "image/png"}],"start_url": ".","display": "standalone", }要求:
- 運行在 https 環境。
- 必須注冊并運行 serviceworker。
- manifest 中必須有 icons,且至少為 144x144 的 PNG 圖像。
- manifest 中 display 設置為 standalone 或者 fullscreen。
- manifest 中必須有 name 或者 short_name。
- manifest 中必須有 start_url。
- manifest 中 prefer_related_applications 未設置或設置為 false。
manifest 的詳細設置信息,可以參考前面寫的 manifest 專題文章。
顯示安裝提示
按要求配置好后,在瀏覽器端打開網站。
Android Chrome 端
從 Chrome 68 以后,當滿足安裝應用的條件時,會立即在瀏覽器底部彈出 “Mini信息條”,用戶單擊信息條時,彈出“添加到主屏幕”的對話框,點擊“添加”后,完成安裝,此時頁面上就出現在應用圖標。
注意:Chrome 68 - 75 的Mini 信息條是無法通過代碼來控制是否展示的,Chrome 76 之后版本支持通過代碼控制顯示。
當用戶點擊 Mini 信息條上的 “X” 時,至少三個月瀏覽器不會再出現 Mini 條的提示,但事件層不受影響,可以通過代碼實現。
PC Chrome 端
Chrome 73 開始支持 PC 端安裝 Web 到桌面
自定義安裝時機
當 Web 應用符合安裝時,會觸發 beforeinstallprompt 事件,并彈出安裝到屏幕的提示,我們可以基于這個事件來控制是否展示安裝提示及何時安裝。
beforeinstallprompt 事件在此應用未安裝的情況下會每次進入頁面都觸發,如果已安裝則不會觸發。當用戶卸載應用后,則會繼續觸發此事件。
安裝提示事件捕獲邏輯:
var installPromptEvent = null;window.addEventListener('beforeinstallprompt', (event) => {event.preventDefault(); // Chrome <= 67 可以阻止顯示installPromptEvent = event; // 拿到事件的引用document.querySelector('#btn-install').disabled = false; // 更新安裝 UI,通知用戶可以安裝 });顯示 prompt 對話框
手動顯示安裝對話框,可以通過調用捕獲的 beforeinstallprompt 事件引用中的prompt() 方法來觸發。
通過事件 userChoice 屬性的 Promise 結果中的 outcome 來獲取。
用戶點擊安裝邏輯:
document.querySelector('#btn-install').addEventListener('click', () => {if( !installPromptEvent ) {return;}installPromptEvent.prompt();installPromptEvent.userChoice.then( choiceResult => {if (choiceResult.outcome === 'accepted') {console.log('用戶已同意添加到桌面')} else {console.log('用戶已取消添加到桌面')}}) })已安裝事件處理
可以通過 appinstalled 來監聽應用是否安裝:
window.addEventListener('appinstalled', (evt) => {console.log('已安裝到桌面屏幕'); });環境判斷
當前應用是通過在瀏覽器里輸入網址打開的,還是通過桌面圖標打開的,可以通過 display-mode 屬性來判斷,然后根據需求設置不同的交互樣式。
假設 manifest 中設置的 display 為 standalone
js 層判斷:
if (window.matchMedia('(display-mode: standalone)').matches) {console.log('display-mode 是 standalone'); }css 層判斷:
@media all and (display-mode: standalone) {/** 自定義樣式 **/ }Safari 判斷:
if (window.navigator.standalone === true) {console.log('display-mode 是 standalone'); }應用的更新
Web 應用安裝到桌面后,對于后面修改 manifest 后的更新問題,目前每個平臺的表現不一樣。
Android 端
在 Android 上,當啟動 Web 應用時,Chrome 會根據實時 manifest 來檢查當前安裝的 manifest。如果需要更新,則在 wifi 環境下自動進入更新隊列。
觸發更新規則:
- 更新檢查僅在啟動 Web 應用時發生。直接啟動 Chrome 不會觸發給定 Web 應用的更新檢查。
- Chrome 會每隔 1 天或每 30 天檢查一次更新。每天檢查更新大多數時間都會發生。在更新服務器無法提供更新的情況下,它會切換到30天的時間間隔。
- 清除 Chrome 的數據(通過Android設置中的“清除所有數據”)會重置更新計時器。
- 如果 Web Manifest URL 未更改,Chrome 將僅更新 Web 應用。如果你將網頁的 manifest 路徑修改,如從 /manifest.json 更改為 /manifest2.json,則 Web 應用將不再更新。(非常不建議這樣做)
- 只有正式版 Chrome(Stable / Beta / Dev / Canary)創建的 Web 應用才會更新。它不適用于 Chromium(org.chromium.chrome)。
- 更新檢查可能會延遲,知道連接可用 wifi。
PC 端
PC 端暫時不支持更新,后續可能會支持。
兼容
目前此特性在各平臺的兼容性如下:
像 IOS 下的 Safari 是支持安裝到桌面的特性,但并沒有走 manifest 的規范。
IOS 上的適配
IOS 針對桌面圖標、啟動畫面、應用文本及主題色需要單獨的特性 Meta 進行設置。
apple-touch-icon:應用圖標
需要在網頁中增加:
<link rel="apple-touch-icon" href="/custom_icon.png">不同分辨率的適配:
<link rel="apple-touch-icon" href="touch-icon-iphone.png"> <link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad.png"> <link rel="apple-touch-icon" sizes="180x180" href="touch-icon-iphone-retina.png"> <link rel="apple-touch-icon" sizes="167x167" href="touch-icon-ipad-retina.png">apple-touch-startup-image:啟動畫面
需要在網頁中增加:
<link rel="apple-touch-startup-image" href="/launch.png">apple-mobile-web-app-title:應用 icon 的標題
默認情況下使用 <title></title> 中的值,需要修改的話需要指定 meta。
<meta name="apple-mobile-web-app-title" content="應用標題">apple-mobile-web-app-status-bar-style:應用狀態欄的外觀樣式
例如設置為黑色:
<meta name="apple-mobile-web-app-status-bar-style" content="black">兼容適配庫
正常來說,所有的特性都要按照規范中的約束來使用,但向上面的 Safari 并沒有按照規范來,這樣會增加開發者的開發成本。
所以這里做一下適配腳本,只寫規范中 manifest 的那些定義部分,剩下的交由腳本來完成。
(function(){function h(){var a=document.head.querySelector('link[rel="manifest"]'),b=a?a.href:"",d=A([b,window.location]);Promise.resolve().then(function(){if(!b)throw'can\'t find <link rel="manifest" href=".." />\'';var a={};"use-credentials"===b.crossOrigin&&(a.credentials="include");return window.fetch(b,a)}).then(function(a){return a.json()}).then(function(a){return B(a,d)}).catch(function(a){return console.warn("pwacompat.js error",a)})}function A(a){for(var b={},d=0;d<a.length;b={c:b.c},++d){b.c=a[d];try{return new URL("",b.c),function(a){return function(b){return(new URL(b,a.c)).toString()}}(b)}catch(n){}}return function(a){return a}}function t(a,b){a=document.createElement(a);for(var d in b)a.setAttribute(d,b[d]);document.head.appendChild(a);return a}function c(a,b){b&&(!0===b&&(b="yes"),t("meta",{name:a,content:b}))}function B(a,b){function d(b,d,f){var k=b.width,c=b.height,e=window.devicePixelRatio;b=u({width:k*e,height:c*e});b.scale(e,e);b.fillStyle=a.background_color||"#f8f9fa";b.fillRect(0,0,k,c);b.translate(k/2,(c-32)/2);b.font="24px HelveticaNeue-CondensedBold";b.fillStyle=r?"white":"black";k=b.measureText(v).width;f&&(c=f.width/e,e=f.height/e,128<e&&(c/=e/128,e=128),48<=c&&48<=e&&(b.drawImage(f,c/-2,e/-2,c,e),b.translate(0,e/2+32)));b.fillText(v,k/-2,0);f=document.createElement("link");f.setAttribute("rel","apple-touch-startup-image");f.setAttribute("media","(orientation: "+d+")");f.setAttribute("href",b.canvas.toDataURL());return f}function n(a){var b=d(window.screen,"portrait",a);a=d({width:window.screen.height,height:window.screen.width},"landscape",a);w.forEach(function(a){return a.remove()});document.head.appendChild(b);document.head.appendChild(a);w.add(b);w.add(a)}var g=a.icons||[];g.sort(function(a,b){return parseInt(b.sizes,10)-parseInt(a.sizes,10)});var x=g.map(function(a){a={rel:"icon",href:b(a.src),sizes:a.sizes};t("link",a);if(p)return a.rel="apple-touch-icon",t("link",a)}),q=a.display;g=-1!==C.indexOf(q);c("mobile-web-app-capable",g);D(a.theme_color||"black");E&&(c("msapplication-starturl",a.start_url||"/"),c("msapplication-TileColor",a.theme_color));document.head.querySelector('[name="theme-color"]')||c("theme-color",a.theme_color);var h=F(a.orientation);c("x5-orientation",h);c("screen-orientation",h);"fullscreen"===q?(c("x5-fullscreen","true"),c("full-screen","yes")):g&&(c("x5-page-mode","app"),c("browsermode","application"));if(p){var r=y(a.background_color||"#f8f9fa"),v=a.name||a.short_name||document.title;(q=G(a.related_applications))&&c("apple-itunes-app","app-id="+q);c("apple-mobile-web-app-capable",g);c("apple-mobile-web-app-title",v);var w=new Set;n(null);if(x.length){var m=x[0],l=new Image;l.crossOrigin="anonymous";l.onload=function(){n(l);if(a.background_color){var b=z(l,a.background_color);null!==b&&(m.href=b,x.slice(1).forEach(function(b){var d=new Image;d.crossOrigin="anonymous";d.onload=function(){var c=z(d,a.background_color,!0);b.href=c};d.src=b.href}))}};l.src=m.href}}}function G(a){var b;(a||[]).filter(function(a){return"itunes"===a.platform}).forEach(function(a){a.id?b=a.id:(a=a.url.match(/id(\d+)/))&&(b=a[1])});return b}function F(a){a=String(a||"");a=a.substr(0,3);return"por"===a?"portrait":"lan"===a?"landscape":""}function D(a){if(p||H){var b=y(a);if(p)c("apple-mobile-web-app-status-bar-style",b?"black":"default");else{try{var d=Windows.UI.ViewManagement.ApplicationView.getForCurrentView().titleBar}catch(n){d=null}null===d?console.debug("UWP no titleBar"):(d.foregroundColor=r(b?"black":"white"),d.backgroundColor=r(a))}}}function r(a){a=m(a);return{r:a[0],g:a[1],b:a[2],a:a[3]}}function m(a){var b=u();b.fillStyle=a;b.fillRect(0,0,1,1);return b.getImageData(0,0,1,1).data}function y(a){a=m(a).map(function(a){a/=255;return.03928>a?a/12.92:Math.pow((a+.055)/1.055,2.4)});return 3<Math.abs(1.05/(.2126*a[0]+.7152*a[1]+.0722*a[2]+.05))}function z(a,b,d){d=void 0===d?!1:d;var c=u(a);c.drawImage(a,0,0);if(!d&&255==c.getImageData(0,0,1,1).data[3])return null;c.globalCompositeOperation="destination-over";c.fillStyle=b;c.fillRect(0,0,a.width,a.height);return c.canvas.toDataURL()}function u(a){a=void 0===a?{width:1,height:1}:a;var b=a.height,c=document.createElement("canvas");c.width=a.width;c.height=b;return c.getContext("2d")}if("fetch"in window){var C=["standalone","fullscreen","minimal-ui"],p=navigator.vendor&&-1!==navigator.vendor.indexOf("Apple"),E=navigator.userAgent&&-1!==navigator.userAgent.indexOf("Edge"),H="undefined"!==typeof Windows;"complete"===document.readyState?h():window.addEventListener("load",h)}})();調用地址:http://unpkg.alipay.com/pwacompat@2.0.9/pwacompat.min.js。
使用:
<link rel="manifest" href="./manifest.json" /> <script src="http://unpkg.alipay.com/pwacompat@2.0.9/pwacompat.min.js" crossorigin="anonymous"></script>博客名稱:王樂平博客
CSDN博客地址:http://blog.csdn.net/lecepin
總結
以上是生活随笔為你收集整理的PWA(Progressive Web App)入门系列:安装 Web 应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式相关书籍推荐
- 下一篇: XE5 Android 开发实现手机打电