使用渐进式 Web 应用 (Chromium) Get started with Progressive Web Apps (Chromium)

渐进式 Web 应用 \ (PWA) 是逐渐增强的 Web 应用Progressive Web Apps (PWAs) are web apps that are progressively enhanced. 渐进式增强功能包括类似应用的功能,如安装、脱机支持和推送通知。The progressive enhancements include app-like features, such as installation, offline support, and push notifications. 还可以打包 PWA 以用于应用商店。You may also package your PWA for app stores. 可能的应用商店包括 Microsoft Store、Google Play、Mac App Store 等。Possible app stores include the Microsoft Store, Google Play, Mac App Store, and more. Microsoft Store 是内置于 Windows 10 的商业应用商店。The Microsoft Store is the commercial app store built into Windows 10.

以下指南通过创建简单的 Web 应用程序并扩展为 PWA,概述了 PWA 基础知识。The following guide gives you an overview of PWA basics by creating a simple web app and extending it as a PWA. 已完成的项目适用于新式浏览器。The finished project works across modern browsers.

提示

可以使用 PWABuilder 创建新的 PWA、增强现有 PWA 或打包 PWA 以用于应用商店。You may use PWABuilder to create a new PWA, enhance your existing PWA, or package your PWA for app stores.

必备条件Prerequisites

创建基本 Web 应用Create a basic web app

若要创建空的 Web 应用,请按照 Node Express App Generator中的步骤操作,并命名你的应用 MySamplePwaTo create an empty web app, follow the steps in Node Express App Generator, and name your app MySamplePwa.

在提示符中,运行以下命令。In the prompt, run the following commands.

npx express-generator --no-view
npm install

这些命令会创建一个空的 Web 应用并安装任何依赖项。The commands create an empty web app and install any dependencies.

现在,你拥有一个简单的功能性 Web 应用。You now have a simple, functional web app. 若要启动 Web 应用,请运行以下命令。To start your web app, run the following command.

npm start

现在浏览 http://localhost:3000 到 以查看新的 Web 应用。Now browse to http://localhost:3000 to view your new web app.

在 localhost 上运行新的 PWA

开始生成 PWAGet started building a PWA

现在你已拥有一个简单的 Web 应用程序,请通过添加 PWA 的三个要求将其扩展为 PWANow that you have a simple web app, extend it as a PWA by adding the three requirements for PWAs:HTTPS、Web应用清单和服务工作者: HTTPS, a Web App Manifest, and a Service Worker.

步骤 1 - 使用 HTTPSStep 1 - Use HTTPS

PWA 平台的关键部分(如 服务工作人员)需要使用 HTTPS。Key parts of the PWA platform, such as Service Workers, require the use of HTTPS. PWA 发布后,必须将其发布到 HTTPS URL。When your PWA goes live, you must publish it to an HTTPS URL.

出于调试目的,Microsoft Edge 还 http://localhost 允许使用 PWA API。For debugging purposes, Microsoft Edge also permits http://localhost to use the PWA APIs.

将 Web 应用发布为实时网站,但请确保服务器配置为 HTTPS。Publish your web app as a live site, but ensure your server is configured for HTTPS. 例如,你可以创建 Azure 免费帐户For example, you may create an Azure free account. Microsoft Azure 应用服务上 托管网站,默认情况下它通过 HTTPS 提供。Host your site on the Microsoft Azure App Service and it is served over HTTPS by default.

以下指南用于生成 http://localhost PWA。The following guide, use http://localhost to build your PWA.

步骤 2 - 创建 Web 应用程序清单Step 2 - Create a Web App Manifest

Web 应用清单是一个 JSON 文件,其中包含有关应用的元数据,如名称、说明、图标等。A Web App Manifest is a JSON file containing metadata about your app, such as name, description, icons, and more.

若要将应用部件清单添加到 Web 应用,请运行以下操作:To add an app manifest to the web app:

  1. In Visual Studio Code, choose File > Open Folder and choose the MySamplePwa directory you created earlier.In Visual Studio Code, choose File > Open Folder and choose the MySamplePwa directory you created earlier.

  2. 选择 Ctrl + N 以创建新文件,并粘贴以下代码段。Select Ctrl+N to create a new file, and paste in the following code snippet.

    {
        "lang": "en-us",
        "name": "My Sample PWA",
        "short_name": "SamplePWA",
        "description": "A sample PWA for testing purposes",
        "start_url": "/",
        "background_color": "#2f3d58",
        "theme_color": "#2f3d58",        
        "orientation": "any",
        "display": "standalone",
        "icons": [
            {
                "src": "/icon512.png",
                "sizes": "512x512"
            }
        ]
    }
    
  3. 将文件另存为 /MySamplePwa/public/manifest.jsonSave the file as /MySamplePwa/public/manifest.json.

  4. 将名为 的 512x512 应用图标图像 icon512.png 添加到 /MySamplePwa/public/imagesAdd a 512x512 app icon image named icon512.png to /MySamplePwa/public/images. 您可以使用示例 图像 进行测试。You may use the sample image for testing purposes.

  5. 在Visual Studio代码"中,打开 /public/index.html ,在 标记内添加以下代码 <head> 段。In Visual Studio Code, open /public/index.html, and add the following code snippet inside the <head> tag.

    <link rel="manifest" href="/manifest.json">
    

步骤 3 - 添加服务工作线程Step 3 - Add a Service Worker

服务工作人员是 PBA 背后的关键技术,可实现脱机支持、高级缓存和运行后台任务等方案,以前仅限于本机应用。Service workers are the key technology behind PWAs, enabling scenarios like offline support, advanced caching, and running background tasks previously limited to native apps.

服务工作者是后台任务,可截获来自 Web 应用的网络请求。Service workers are background tasks that intercept network requests from your web app. 即使 PWA 未运行,服务工作人员也尝试完成任务。Service workers attempt to complete tasks, even when your PWA is not running. 任务包括以下操作。Tasks include the following actions.

  • 为来自缓存的已请求资源提供服务Serving requested resources from a cache
  • 发送推送通知Sending push notifications
  • 运行后台提取任务Running background fetch tasks
  • 标记图标Badging icons
  • 和更多信息and more

服务工作者在一个特殊的 JavaScript 文件中定义。Service workers are defined in a special JavaScript file. 有关详细信息,请导航到"使用服务工作者和服务工作者 API"。For more information, navigate to Using Service Workers and Service Worker API.

若要在项目中生成服务工作器,请使用 PWA Builder 中的缓存 一个网络服务工作 器方法To build a service worker in your project, use the Cache-first network service worker recipe from PWA Builder.

  1. 导航到 pwabuilder.com/serviceworker,选择 "缓存第一个网络 服务工作线程",然后选择" 下载" 按钮。Navigate to pwabuilder.com/serviceworker, select the Cache-first network service worker, and select the Download button. 下载的文件包含以下文件:The downloaded file contains the following files:

    • pwabuilder-sw-register.js
    • pwabuilder-sw.js
  2. 将下载的文件复制到 Web public 应用项目中的文件夹。Copy the downloaded files to the public folder in your web app project.

  3. 在Visual Studio代码"中 /public/index.html ,打开 标记内并添加以下代码 <head> 段。In Visual Studio Code, open /public/index.html and add the following code snippet inside the <head> tag.

    <script type="module" src="/pwabuilder-sw-register.js"></script>
    

您的 Web 应用现在具有使用缓存第一策略的服务工作器。Your web app now has a service worker that uses the cache-first strategy. 新服务工作者首先从缓存获取资源,然后仅根据需要从网络获取资源。You new service worker fetches resources from the cache first, and from the network only as needed. 缓存的资源包括图像、JavaScript、CSS 和 HTML。Cached resources include images, JavaScript, CSS, and HTML.

使用以下步骤确认服务工作线程是否运行。Use the following steps to confirm that your service worker runs.

  1. 使用 导航到 Web 应用 http://localhost:3000Navigate to your web app using http://localhost:3000. 如果 Web 应用不可用,请运行以下命令。If your web app is not available, run the following command.

    npm start
    
  2. 在 Microsoft Edge 中, F12 选择打开 Microsoft Edge DevTools。In Microsoft Edge, select F12 to open the Microsoft Edge DevTools. 选择 "应用程序",然后选择" 服务 工作人员"以查看服务工作人员。Select Application, then Service Workers to view the service workers. 如果未显示服务工作线程,则刷新页面。If the service worker is not displayed, refresh the page.

    Microsoft Edge DevTools 服务工作器概述

  3. 通过展开缓存存储查看服务工作 器缓存 ,然后选择 pwabuilder-precacheView the service worker cache by expanding Cache Storage and select pwabuilder-precache. 应显示服务工作线程缓存的所有资源。All of the resources cached by the service worker should be displayed. 服务工作者缓存的资源包括应用程序图标、应用程序清单、CSS 和 JavaScript 文件。The resources cached by the service worker include the app icon, app manifest, CSS, and JavaScript files.

    Microsoft Edge DevTools 中的服务工作器缓存

  4. 尝试将 PWA 作为脱机应用。Try your PWA as an offline app. 在 Microsoft Edge DevTools \ () 中,选择"网络",然后将 F12 "联机状态"更改为"脱机"。 ****In Microsoft Edge DevTools (F12), choose Network then change the Online status to Offline.

    在 Microsoft Edge DevTools 中将应用设置为脱机模式

  5. 刷新你的应用,它应显示用于从缓存提供应用资源的脱机机制。Refresh your app and it should display the offline mechanism for serving the resources of your app from the cache.

    脱机运行的 PWA

将推送通知添加到 PWAAdd push notifications to your PWA

通过完成以下任务,可以创建支持推送通知的 PWA。You may create PWAs that support push notifications by completing the following tasks.

  1. 使用推送 API 订阅 消息传递服务Subscribe to a messaging service using the Push API
  2. 使用通知 API 从服务接收消息时显示 Toast 消息Display a toast message when a message is received from the service using the Notifications API

与服务工作人员一样,推送通知 API 是基于标准的 API。Just like with Service Workers, the push notification APIs are standards-based APIs. 推送通知 API 跨浏览器工作,因此代码应在支持 PA 的任何地方运行。The push notification APIs work across browsers, so your code should work everywhere that PWAs are supported. 有关将推送消息发送到服务器上不同浏览器的信息,请导航到"Web 推送"。For more information about delivering push messages to different browsers on your server, navigate to Web-Push.

以下步骤改编自 Mozilla 提供的 Push Rich Demo in Service Worker Cookbook, 该演示具有大量其他有用的 Web 推送和服务工作者方法。The following steps have been adapted from the Push Rich Demo in Service Worker Cookbook provided by Mozilla, which has a number of other useful Web Push and service worker recipes.

步骤 1 - 生成 VAPID 密钥Step 1 - Generate VAPID keys

推送通知需要 VAPID \ (自愿应用程序服务器标识) 密钥才能将推送通知发送到 PWA 客户端。Push notifications require VAPID (Voluntary Application Server Identification) keys in order to send push messages to the PWA client. 联机 \ (提供了多个 VAPID 密钥生成器,例如,vapidkeys.com ) 。There are several VAPID key generators available online (for example, vapidkeys.com). 生成后,应获取包含公钥和私钥的 JSON 对象。After generation, you should get a JSON object containing a public and private key. 保存密钥,以执行以下教程中的稍后步骤。Save the keys for later steps in the following tutorial. 有关 VAPID 和 WebPush 的信息,请导航到使用 Mozilla 推送服务发送 VAPID 标识的 WebPush 通知For information about VAPID and WebPush, navigate to Sending VAPID identified WebPush Notifications using the Mozilla Push Service.

步骤 2 - 订阅推送通知Step 2 - Subscribe to push notifications

服务工作人员在 PWA 中处理推送事件和 Toast 通知交互。Service workers handle push events and toast notification interactions in your PWA. 若要订阅PWA推送通知,请确保满足以下条件。To subscribe the PWA to server push notifications, ensure the following conditions are met.

  • 你的PWA安装、激活和注册Your PWA is installed, active, and registered
  • 用于完成订阅任务的代码位于应用程序主 UI 线程PWAYour code to complete the subscription task is on the main UI thread of the PWA
  • 您具有网络连接You have network connectivity

在新建推送订阅之前,Microsoft Edge验证用户是否被授予PWA接收通知的权限。Before a new push subscription is created, Microsoft Edge verifies if the user granted the PWA permission to receive notifications. 如果没有,浏览器会提示用户授予权限。If not, the user is prompted by the browser for permission. 如果权限被拒绝,则引发 registration.pushManager.subscribe 的请求将引发 DOMException ,必须处理。If the permission is denied, the request to registration.pushManager.subscribe throws a DOMException, which must be handled. 有关权限管理 More on, navigate to Push Notifications in Microsoft Edge.For more on permission management, navigate to Push Notifications in Microsoft Edge.

在文件中 pwabuilder-sw-register.js ,附加以下代码段。In your pwabuilder-sw-register.js file, append the following code snippet.

// Ask the user for permission to send push notifications.
navigator.serviceWorker.ready
    .then(function (registration) {
        // Check if the user has an existing subscription
        return registration.pushManager.getSubscription()
            .then(function (subscription) {
                if (subscription) {
                    return subscription;
                }
                
                const vapidPublicKey = "PASTE YOUR PUBLIC VAPID KEY HERE";             
                return registration.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: urlBase64ToUint8Array(vapidPublicKey)
                });
            });
    });

// Utility function for browser interoperability
function urlBase64ToUint8Array(base64String) {
    var padding = '='.repeat((4 - base64String.length % 4) % 4);
    var base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');
        
    var rawData = window.atob(base64);
    var outputArray = new Uint8Array(rawData.length);
    
    for (var i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}

有关详细信息,请导航到PushManager 和 Web-Push。For more information, navigate to PushManager and Web-Push.

步骤 3 - 侦听推送通知Step 3 - Listen for push notifications

在服务中创建订阅PWA,将处理程序添加到服务工作者以响应推送事件。After a subscription is created in your PWA, add handlers to the service worker to respond to push events. 推送事件从服务器发送以显示 Toast 通知。Push event are sent from the server to display toast notifications. Toast 通知显示已接收邮件的数据。Toast notifications display data for a received message. 若要完成以下任务,必须添加 click 处理程序。To complete the following tasks, you must add a click handler.

  • 消除 Toast 通知Dismiss the toast notification
  • 打开、聚焦或打开所有打开的窗口并聚焦Open, focus, or open and focus any open windows
  • 打开并聚焦一个新窗口,以显示PWA页Open and focus a new window to display a PWA client page

在你的 pwabuilder-sw.js 文件中,添加以下处理程序。In your pwabuilder-sw.js file, add the following handlers.

// Respond to a server push with a user notification.
self.addEventListener('push', function (event) {
    if (Notification.permission === "granted") {
        const notificationText = event.data.text();
        const showNotification = self.registration.showNotification('Sample PWA', {
            body: notificationText,
            icon: 'images/icon512.png'
        });
        // Ensure the toast notification is displayed before exiting the function.
        event.waitUntil(showNotification);
    }
});

// Respond to the user selecting the toast notification.
self.addEventListener('notificationclick', function (event) {
    console.log('On notification click: ', event.notification.tag);
    event.notification.close();
    
    // This attempts to display the current notification if it is already open and then focuses on it.
    event.waitUntil(clients.matchAll({
        type: 'window'
    }).then(function (clientList) {
        for (var i = 0; i < clientList.length; i++) {
            var client = clientList[i];
            if (client.url == 'http://localhost:1337/' && 'focus' in client)
                return client.focus();
        }
        if (clients.openWindow)
            return clients.openWindow('/');
    }));
});

步骤 4 - 试用Step 4 - Try it out

若要为用户测试推送通知PWA,请完成以下步骤。To test push notifications for your PWA, complete the following steps.

  1. 导航到 PWA http://localhost:3000 。。Navigate to your PWA at http://localhost:3000. 当服务工作者激活并尝试订阅PWA推送通知时,Microsoft Edge提示你允许PWA显示通知。When your service worker activates and attempts to subscribe your PWA to push notifications, Microsoft Edge prompts you to allow your PWA to show notifications. 选择 "允许"。Select Allow.

    用于启用通知的权限对话框

  2. 模拟服务器端推送通知。Simulate a server-side push notification. 在浏览器中PWA打开应用后,选择 http://localhost:3000 F12 打开 DevTools。With your PWA opened at http://localhost:3000 in your browser, select F12 to open the DevTools. 选择 " > 应用程序服务工作者 > 推送"将测试推送通知发送到PWA。Choose Application > Service Worker > Push to send a test push notification to your PWA.

    推送通知应显示在任务栏附近。A push notification should display near the taskbar.

    从 DevTools 推送通知

    如果未选择 \ (或 activate) toast 通知,系统会在几秒钟后自动将其关闭,Windows操作中心中将其排好队列。If you do not select (or activate) a toast notification, the system automatically dismisses it after several seconds and queues it in your Windows Action Center.

    Windows操作中心中的通知

后续步骤Next steps

以下步骤包括其他任务,可帮助你了解构建实际 PBA。The following steps include additional tasks to help you understand building real-world PWAs.

另请参阅See also