Categories: From web to PWA date: 2019-07-12 17:00:00 Tags: -JavaScript Categories

Last time we learned about the Sevice worker, which can be used for client resource caching. However, the use of sevice worker goes far beyond that. It can intercept all client HTTP requests and store the returned response, so as to achieve normal offline client access. The feature of offline access easily reminds people of the ability of Native App. In fact, Sevice worker can indeed make Web pages “Native” with other technologies, which is what we often call PWA.

PWA is introduced

PWA(Progress Web App) is a progressive web app that is committed to realizing user experience similar to native apps in web applications. It was proposed by Google in 2016. Although it is a Web page, it has the ability of offline access and push through some new technologies. At the same time, compared with native APP, it has the characteristics of convenient installation and update.

Can access the LAVAS of baidu home page, for more information about the pwa API lavas.baidu.com/pwa/README

A standard PWA should have the following characteristics

  • Discoverable: Content can be discovered by search engines.
  • Installable, which can appear on the device’s home screen.
  • Linkable, you can simply share it with a URL.
  • Network Independent, which can run offline or with poor Internet speeds.
  • Progressive, which is still available on older browsers, is fully functional on newer browsers.
  • Re-engageable, which can send notifications whenever there is new content.
  • Responsive, it works on any device with a screen and browser — including mobile phones, tablets, laptops, TVS, refrigerators, etc.
  • Safe, the connection between you and your app is secure and prevents third parties from accessing your sensitive data.

Browser compatibility

The realization of the PWA

On a technical level, the PWA should implement the following functions:

  • Offline accessibility
  • It can be accessed from the desktop icon
  • User push can be realized

Offline cache sevice worker

Sevice Worker is a proxy server written by JS that runs between applications and browsers, providing advanced and sustainable background processing capabilities for Web applications. It creates an effective offline experience, intercepts network requests and takes appropriate action based on whether the network is available and whether updated resources reside on the server.

Sevice worker: Front-end static resource caching Sevice worker

By setting the offline cache rule of resources in the Sevice worker, the offline access capability can be provided for Web applications.

Note: PWA requires web applications to have offline access.

Add the site to the home screen

Allowing sites to be added to the home screen is an important feature provided by PWA. While some browsers already support adding web shortcuts to the home screen to quickly open sites, PWA is adding more functionality and styles to the home screen than just a web shortcut, making PWA a more native experience. The functionality added to the desktop by PWA relies on manifest.json, which can be used to configure the application’s icon, name, and other information.

implementation

  1. Add manifest.json to your project directory
// Manifest.json file configuration
{
    "short_name": "Short name"."name": "That's a full name.".// Define the name
    "icons": [ // Customize the icon
        {
            "src": "love0.png"."type": "image/png"."sizes": "48x48"
        },
        {
            "src": "love.png"."type": "image/png"."sizes": "144x144"}]."start_url": "index.html".// Specify the url to open the application
    "display": "fullscreen".// Apply the open display window style
    "theme_color": "#ff4c43" // Set the color of the application window when it opens
}
Copy the code
  1. Introduce the manifest.json file on the project’s home page
<link rel="manifest" href="manifest.json">
Copy the code
  1. To open the website and install the PWA, you need to manually install the PWA on the PC. In this example, you need to enable the enable pWA function in The Chrome browser on the MAC OS. Enter chrome://flags in the address bar. Set the Desktop PWAs to Enabled and restart the browser

Open the Web page, and if the Web page supports PWA, you can install the application from more in the upper right corner of the browser

Json files write rules that are valid once installed. To modify the manifest information to take effect, you need to uninstall the old application and reinstall it. You can uninstall the app by clicking three dots in the upper right corner of the PWA, or delete the app from the folder.

Notifications and alerts

Pwa’s Push capability is implemented through the Push API, which is responsible for pushing messages, and the Notification API, which is responsible for displaying Notifications.

Being pushed

How web push works

The Push Service can save the message queue when the user is offline and send the message when the user is online. In addition, the Push Service will generate a unique URL for each browser that initiates the subscription, so that when we Push a message to the server, after we Push to this URL, the Push Service will know which browser to notify. The field that stores the URL information is the endpoint.

  1. Subscribe: The browser (client) needs to Subscribe to the Push Service and gets a PushSubscription object
  2. Monitor: The subscription operation communicates with the Push Service to generate the corresponding subscription information. The Push Service maintains the corresponding information and keeps contact with the client based on this information
  3. Distribute Push Resource: When a browser subscription is completed, it gets information about the subscription (present in the PushSubscription object), which we need to send to our own server for saving on the server.
  4. Push Message: The server sends a Message to the Push Service.
  5. Push Message: The Push Service receives a Push Message, compares it to the maintained subscription list, and sends the Message to the specified client
  • Google push Service is not available in China, so let’s use Firefox as an example

Initiate subscriptions and save subscription information

// Register sevice worker
if ('serviceWorker' in navigator) {
    var publicKey = 'BOEQSjdhorIf8M0XFNlwohK3sTzO9iJwvbYU-fuXRF0tvRpPPMGO6d_gJC_pUQwBT7wD8rKutpNTFHOHN3VqJ0A';
    registerServiceWorker()
        .then(registration= > {
            console.log('ServiceWorker registered successfully! Scope: ', registration.scope) 
            // Initiate a subscription push sevice returns a unique identifier to the client
            return subscribeUserToPush(registration, publicKey); 
        })
        .then(subscription= > {
            var body = {subscription: subscription};
            // Stores the generated client subscription information on its own server
            return sendSubscriptionToServer(JSON.stringify(body));
        })
        .then(res= > {
            console.log(res);
        })
        .catch(err= > {
            console.log(err)
        });
}
/ / register
function registerServiceWorker() {
    return navigator.serviceWorker.register('sw.js', {scope: '/'});
}

// Initiate a subscription
function subscribeUserToPush(registration, publicKey) {
    var subscribeOptions = {
        userVisibleOnly: true.// Whether the push needs to be explicitly sent to the user
        applicationServerKey: publicKey 
    }; 
    return registration.pushManager.subscribe(subscribeOptions).then(function (pushSubscription) {
        console.log('Received PushSubscription: '.JSON.stringify(pushSubscription));
        return pushSubscription;
    });
}
Copy the code
  • PublicKey ensures secure push and is saved on the client.
  • The client through registration. PushManager. Subscribepush method call push server, at the same time in the parameter Settings and push for the public key, then push server will be subscription information back to the client after public key encryption processing
  • The client sends encrypted subscription information to its own server store, subscription subscription, which the server must use to push to the client.

Send push

Server code:

const webpush = require('web-push');

// pWA pushes information
const pushMessage = async (ctx) => {
	/** * VAPID value * here can be replaced with the actual value in your business */
	const vapidKeys = {
	    publicKey: 'BOEQSjdhorIf8M0XFNlwohK3sTzO9iJwvbYU-fuXRF0tvRpPPMGO6d_gJC_pUQwBT7wD8rKutpNTFHOHN3VqJ0A'.privateKey: 'TVe_nJlciDOn130gFyFYP8UiGxxWd3QdH6C5axXpSgM'
	};

	// Set the VAPID value of the web-push
	webpush.setVapidDetails(
	    'mailto:[email protected]',
	    vapidKeys.publicKey,
	    vapidKeys.privateKey
	);

	 // Client information to be pushed can be obtained from the database based on service scenarios
	let subscription = {
		 	endpoint:'https://updates.push.services.mozilla.com/wpush/v2/gAAAAABdJ-rl96NWkfof3N3cHVJ0vO2-i_9K5eg2WoS9XumIJyYSp-Eeu2MpEV0qoisZ ipI2mbsYRvceM7F_62QJ0hjsAES8qGflnMmkB_UZjzIi8dI5SGIGrCh2RPurGdrdVL4o9yVo6dx8RfI6MHIqNyaqxYTOC_jH61EtSP9inn_eYdMRw3c'.keys: {auth:'ehJWs1HwbokEKzf7VDhORQ'.p256dh:'BBNLr0Qjib3QOHN2sFnjWR9Xtcm0kGSzDbqyh7FoXBalUD_yqRBCgBa8oXYIRL_vhdTW5x0hNI_vc_noT_1ekPc'
		 	}
		},
		data = {
			title : 'I'm the notification title'.body : 'We have received a push message.'.icon : 'love.png'.tag : 'simple-push-demo-notification-tag'
		}

	webpush.sendNotification(subscription, data).then(data= > {
        console.log('Push service data :'.JSON.stringify(data));
        ctx.body = {
			success:true.message:'Push message succeeded! '
		}
        return;
    }).catch(err= > {
        // Check the status code, 440 and 410 indicate invalid
        if (err.statusCode === 410 || err.statusCode === 404) {
            console.log('This subscription is no longer valid');
        }
        else {
            console.log(err); }})}Copy the code
  • The server stores the privateKey, which corresponds to the publicKey that the client sends subscriptions to, ensuring that other servers cannot push messages to the client at will, even if the subscription is given.
  • Send push relies on the Web push library and can be installed by NPM install web-push
  • Subscription can send a push message to a specified client by calling the webpush. SendNotification method and passing in unique identifying information

Receive push messages and display them

Notification is responsible for passing messages from the SW to the client

/ / sw. Js file
self.addEventListener('push'.function(event) {
    var 
  var body = 'We have received a push message.'; // Spit out the content
  var icon = '/love.png'; // The icon displayed on the push
  var tag = 'simple-push-demo-notification-tag'; // Push messages with the same tag will be automatically overwritten to prevent poor user experience caused by too many push messages
  var data = {
    doge: {
        wow: 'such amaze notification data'}}; event.waitUntil( self.registration.showNotification(title, {body: body,
      icon: icon,
      tag: tag,
      data: data
    })
  );
});
self.addEventListener('notificationclick', event => {
    console.log('User clicked push message')});Copy the code
  • Registration. ShowNotification is responsible for the push message
  • Different systems have different push styles
  • When a user clicks on a pushMessage, notificationclick can listen to it. Depending on the business scenario, postMan can add different behavior to the pushMessage interface. The result is as follows: