Categories
Online Marketing

Discoverability & Analytics

Your PWA is still a webpage that customers can find in their usual ways. You want to apply reasonable search engine optimization and ensure the page is available to search engines. You can use JavaScript on your pages and Google will index it as long as you follow some best practices. You can use the fetch as Google tool from the Google webmasters site to see how your app looks when crawled discoverability helps get customers to your site.

But how can you measure their behaviors once they get there? That’s where analytics comes in Google Analytics is a service that collects processes and reports, data about an applications, use patterns and performance. Adding Google Analytics to a web application enables the collection of data like visitor traffic, user agent, the user’s location, etc. This data is sent to Google Analytics servers where it’s processed.

The reports are available in the Google Analytics web interface and through a reporting API, Google Analytics is free and highly customisable. Integrating Google Analytics is simple. First, you must create a Google Analytics account. Each account has properties, and these aren’t JavaScript properties, but refer to individual applications or websites. Google Analytics then generates a tracking snippet for each property.

This is a piece of JavaScript that you pasted into your page. It sends data to the Google Analytics back-end. You can also use the analytics library to create custom analytics, such as tracking specific user actions or tracking push notifications. I want to say a bit more about properties. An account has properties that represent individual collections of data. These properties have property, IDs, also called tracking IDs.

That identify them to Google Analytics if an account represents a company. One property in that account might represent the company’s website, while another property might represent the company’s mobile application. If you only have one app, the simplest scenario is to create a single Google Analytics, account and add a single property to that account. This is the key part of the tracking snippet.

The entire snippet needs to be pasted into every page. You want to track at a high level when this script runs. It creates an async script tag that downloads analytics AS the analytics library it defines the GA function called the command queue. It creates a tracker that gathers user data and it sends this data as a pageview hit via HTTP request to Google Analytics. This data is analyzed in stored in your analytics account.

In addition to the data gathered by tracker creation, the page view event allows Google Analytics to infer what pages the user is visiting, how long they are visiting them and in what order for simpler applications. This is the only coding required note. You can replace analytics GS with analytics underscore debug KS for console debugging. Using this version will log detailed messages to the console for each hit, sent it also logs warnings and errors for your tracking code.

The data is sent to Google Analytics backend where it is processed into reports. These reports are available through the Google Analytics dashboard. Here is the audience overview interface. Here you can see general information such as page view, records bounce rate, ratio of new and returning visitors and other statistics. You can also see specific information like a visitor’s language, country, city, browser operating system, service provider, screen resolution and device.

Here we are looking at the user City, it’s also possible to view the analytics information in real time. This interface allows you to see hits as they occur on your site. I encourage you to take some time and explore there’s an extensive set of features in the dashboard. You should explore the standard reports and look at creating your own. Knowing how to use analytics for improving your business or increasing revenue is a skill within itself.

Fortunately, the Google Analytics Academy offers a free set of online courses. Google Analytics supports custom events that allow fine, grained analysis of user behavior. This code uses the G a command Q, which is defined in the tracking snippet. The send command is used to send an analytics event. Values associated with the event are as parameters. These values represent the event, category event, action and event label.

All of these are arbitrary and used to organize events. These custom events allow us to deeply understand user interactions with our site. For example, here we are sending a view more event. This might be used to indicate that the user has viewed an item from our site. The event label tells us that it was a premium product. I mentioned earlier that you might use events to track push notifications.

You can add events to fire when users subscribe or unsubscribe to push notifications as well as when there is an error in a subscription process. This can give you an understanding of how many users are subscribing or unsubscribing to your app here. We send a subscribe event, letting us know that a user has subscribed to our notifications. Let’s talk about what happens when analytics meets service workers, they won’t work without a little help.

That’s because the service worker script runs on its own thread and doesn’t have access to the GA command queue object established by the tracking snippet code on the main thread. It also requires the window object. Service workers must use the measurement protocol API instead of the command Q. This is a simple set of HTTP parameters documented at the Google Analytics site. Here’s an example of recording when the user closes a push notification.

The service worker manages the notification lifecycle, so it receives a notification close event when the event fires, the service worker, sends a hit via post with tracking ID custom event parameters and the required parameters for the API. Remember that we don’t want this service worker to shut down before we complete the post, so we wrap this code in event. Wait until since hits are effectively HTTP requests, they can’t be sent if the user is offline using service worker and indexeddb hits can be stored when users are offline and sent it a later time when they have reconnected.

Fortunately, the SW offline, google analytics and PM package abstracts this process for us to integrate offline analytics, install the package in your project with the npm install command. Then, in the service worker script import, the offline, google analytics import, je and initialize. The google and google analytics object. This adds a fetch event handler to the serviceworker that only listens for requests made to the Google Analytics domain.

The handler attempts to send Google Analytics normally if the network request fails, it will be stored in indexdb. Instead, the stored hits will be resent when online. You can test this behavior by enabling offline mode in developer tools and then triggering Google Analytics hits on your app indexdb will show a list of urls that represent the unsent hit requests. You may need to click the Refresh icon inside the indexdb interface to see them.

If you disable offline mode and refresh the page, you should see that the urls are cleared indicating that they have been sent now. It’s your turn. Go to the analytics API lab in there. You will create an account, add analytics to an app look at the results and make this work in a progressive web, app good luck and have fun if you’re an instructor. This final slide links to more information on analytics.

If you’re a student, these links can be found in your textbook. You may want to use these while you are working on the lab. There are additional slides at the end of this presentation that show the major analytic screens and explain how to get there, use these to deepen your knowledge or create live demonstrations. You


 

Categories
Online Marketing

Gulp Setup – Progressive Web App Training

Modern web development involves quite a few tasks, running servers, optimizing images and processing source code. Now these are the kinds of manual tasks that you can automate with: gulp grunt make or other build tools. The world of build tools is constantly changing, but we chose gulp here for its relative longevity and its relative simplicity simply put gulp reads: a file called the gulp file to tell it what to do it then processes your source files, transforms them and writes the results To a build directory, this is a sample golf rjs file, it’s written in JavaScript with a couple of no js’ extensions for loading, other files, the require statements of the top load, the core gulp commands and the gulp interface to uglify.

These are known as gulp plugins and by the way, uglify is a program to compress and minify javascript. Now, gulp files are divided into a series of tasks. A task might run a server minify some code or even delete files. Each task should be one self-contained action. We define a task named uglify j/s and write some JavaScript to implement it. The gulp dots sauce task reads all the J’s files from source J s.

We then pass all those files into the uglify tool using the pipe command. Now the output of each command is ready to pipe into the next, so we use the gulp nest command to write the result into new files under dist J s. Snap formerly gulp is a cross-platform streaming task. Runner that lets developers automate many development tasks at a high level, gulp reads: files as streams and pipes the streams to different tasks.

These tasks are code based and use. Plugins the tasks modify the files building source files into production files to get an idea of what gulp can do check the list of gulp recipes on github gulp is an ode package and the plugins that it uses are also node packages. So you need to install node.Js first, this also installs the node package manager, and you should also enable gulp from the command-line and to do this install the gulp CLI package.

You can then go into your project or create a new one and have NPM install the gulp plugins. You need into your project right, your gulp file, j/s, and you can begin using gulp from the command-line here’s an example of creating a project and installing gulp plugins. The first line creates a new NPM project. This generates a package JSON file that lists your project’s plugins. The following commands install various example plugins, including gulp itself: the save dev flag updates the package JSON file with the corresponding plug-in the plugins are installed in a node modules directory with this method, you can easily reinstall all plugins and their dependencies later by using the package.

Json file, rather than reinstalling each plug-in individually, now note that plugins, a B and C a imaginary we’re just using those names to show how plugins work once the plugins are installed. They need to be loaded into the gulp file using require now you’re ready to define tasks. This task is named task ABC. It takes file from the some sources, files path and pipes and through functions from each of the plugins which modify the files.

The processed files are passed to gulp tests, which writes the files to some destination path. The task we just defined can be run from the command line by typing gulp space and the task name in this case. It’s gulp space task, ABC here’s a set of links for learning more about gulp ins. We’ve also built a code lab that takes you through common tasks, follow the link to get to the lab. Now don’t worry if you’ve missed any details, just look at the gulp documentation and our to find out more.

We supply gulp files with our code labs, so you’ll be all set for now. Let’s get back to writing PWA s and i’ll see you soon.


 

Categories
Online Marketing

Installing Google Analytics – Progressive Web App Training

We want to know what users are doing on our site, which pages are popular, whether users follow the paths we expect and if anything goes wrong. Analytics is all about collecting measurements of user activity on the site. Google Analytics is a service that collects processes and reports.

Data about an applications, use patterns and performance, adding Google Analytics to a web application enables the collection of data like visitor traffic, user agent, the user’s location, etc. This data is sent to Google Analytics servers where it is processed. The reports are available in the Google Analytics web interface and throw reporting API. Google Analytics is free and highly customizable.

Integrating Google Analytics is simple. First, you must create a Google Analytics account. Each account has properties, these aren’t JavaScript properties, but refer to individual applications or websites. Google Analytics then generates a tracking snippet for each property. This is a piece of JavaScript that you pasted into your page. It sends data to Google Analytics back-end. You can also use the analytics library to create custom analytics, such as tracking specific user actions or tracking push notifications.

I want to say a bit more about properties. An account has properties that represent individual collections of data. These properties have property, IDs, also called tracking IDs. That identify them to Google Analytics if an account represents a company. One property in that account might represent the company’s website, while another property might represent the company’s mobile app. If you only have one app, the simplest scenario is to create a single Google Analytics account and add a single property.

To that account. The analytics server will then generate a custom bit of JavaScript matching your account and property. This is the tracking snippets. This is the key part of the tracking snippet. The entire snippet needs to be pasted into every page. You want to track at a high level when this script runs. It creates an a syncs Tagg that downloads analytics is the analytics library defines the GA function called the command.

Q creates a tracker that gathers user data and sends this data as a pageview hit via HTTP request to Google Analytics. This data is analyzed and stored in your analytics account, in addition to the data gathered by tracker creation, the page view event allows Google Analytics to infer what pages the user is visiting, how long they are visiting them and in what order for simpler applications. This is the only coding required note that you can replace analytics j/s with analytics underscore debug KS for console debugging.

Using this version will log detailed messages to the console for each hit, sent it also logs warnings and errors for your tracking code. The data is sent to Google Analytics back-end where it is processed into reports. These reports are available through the Google Analytics dashboard. Here is the audience overview interface. Here you can see general information such as page view, records bounce rate, ratio of new and returning visitors and other statistics, it’s also possible to view analytics information in real time.

This interface allows you to see hits as they occur on your site. I encourage you to take some time and explore there’s an extensive set of features in the dashboard. You should explore the standard reports and look at creating your own. Knowing how to use analytics effectively is a skill in itself. Fortunately, the Google Analytics Academy offers a free set of online courses. I encourage you to install analytics on some of your sites.

If you haven’t already check out the free analytics Academy courses as well, then once you’re comfortable with analytics, come back and I’ll show you how to integrate analytics into a PWA. Thanks for reading and I’ll see you soon,


 

Categories
Online Marketing

Turn a web app into a PWA in 10 minutes

I will show you how to turn an existing application into a progressive web application using just a plain JavaScript API. So if you want to see how we built this application, go ahead and check out the first article, let’s get started, so our application is a newsreader. We have a plain application with just some news articles being displayed.

What I want to do now is turn this application into a progressive web application. What I want to be able to do is install this application on devices that support it and have it run offline, so that we can see some previously fetched news, even if we are offline now, when we’re building a progressive web application, a good place to start Is the application tab in chrome, dev tools? It will essentially guide you through the steps needed we’ll start up here at the manifest tab and right now we can see that there’s no manifest detected.

So that’s a good indication of what we need to do. First, so we’ll jump into our code here and we will create a new file a any test web any first. The web manifest is just a JSON file containing some of the basic information about our application. Like its name, what URL should start some basic things like icons as such once we have, the file itself will go into our index file and we’ll link to our manifest.

So just the same way as we would link to a style sheet. We will link to our manifest file, we’ll save this go back to our browser refresh, and we should be able to see that we have our manifest file here. So we can see our icons, we can see the name. We can also see that there’s an add to homescreen link here now, so this is a good way for us to check if our application is in fact installable. So let’s click on it.

Ok, so we can see that we can’t install this because there’s no matching serviceworker detected, so that’s again a good indication on what we need to do next, so I’ll create a new service worker phone service worker jeaious, if you’re not familiar with a service worker, it’s Essentially, a JavaScript worker that sits between your application and the network. This means that whenever your application goes out to the network, it will pass through the service worker it’ll.

Allow us to do things like caching in between, so we can decide ourselves whether or not we actually want to go out to the network for a particular resource. We can also decide that we can return some things from our cache if we are offline. So this will allow us to make our application work offline. Ok, so we have our service worker file. The next part of using a service worker is registering it, so we’ll go into our load listener here and once we’ve fetched our noose, the user is already happily using the application.

We can go ahead and register our service worker call. This register SW so we’ll implement this service worker register. The registration looks something like this, so we have a quick feature detection. First, we want to make sure that the browser actually does support service worker before we try to register it. We then call service worker dot register on the navigator object and pass in our service worker file.

So let’s save this: let’s go back to our application refresh and see if we got an service worker, it’s a little bit smaller. So we can now see that we do in fact have a service worker file, while you’re developing. It’s really good to keep this update on reload check that way. You’ll get all the new changes that you make to service, who are very visible immediately. Instead of having to close the window and reopen it, which would normally be required for a service worker to take take effect so we’ll go back and turn the manifest file here, our manifest tab will click on add to homescreen and see.

If we’re, there already turns out worse able to install the application, because the browser is telling us that the page doesn’t work offline. Now that makes sense, because our Service Worker file is completely empty and the Service Worker is a completely event-driven thing, so it can only run code if some event triggers that. The first event that gets triggered on a serviceworker is the install event.

So we’ll add a listener for the install event on the serviceworker itself. Typically, what we want to do in the install event is cache. Some like static files that we know our application will need the way we do that is by using the cache API. So we’ll open up a cache with a given name, and then we will add a list of static assets that we have. So, let’s define our cache net first cache name, let’s call this use v1 and then we’ll define an area of the different static assets that we have so our index, page CSS and JavaScript files, and so on.

We’ll save those. The final thing that we do here is we call skip waiting which will cost the serviceworker to move into the activate face the activate faces, essentially when a new service worker takes over from any previous service workers. Normally, what you would do here is clean out any previous versions of your cache. For instance, what I’m calling here is self got clients that claim which will essentially tell my service worker to start servicing the running application immediately, instead of waiting until the next time.

We get to this application. This will allow us to keep start fetching and caching, the newest articles already on the first time, all right so we’ll go back to our application, will refresh here make sure that we have a new Service Worker up and running. We can go in and check in our cache tab here that everything that we defined in that static array did get cashed now that we have stuff in the cache.

Let’s go back to our manifest tab here and see if we’re able to add this to the home screen, it turns out that we are still not able to do add this to our home screen, because it’s still not working offline. The way the browser knows that it’s not working offline is because, even though we did put stuff into the cache we haven’t used any of that stuff, so we still need to prove to the browser that we work offline.

The way we do that is by listening for yet another event, so we’ll add a listener for the fetch event. Now this listener will get. Essentially, this listener will intercept any fetch request going from our application out to the network, so this will allow us to handle these requests any way we want to. Essentially what I’m doing here is I’m differentiating on traffic based on where it’s going. So if we’re fetching something from our own application, so that would be any of these static resources.

We want to check first, if it’s in our cache and return that, and if not, then we could go to the network. If we’re fetching news, though, what we want to do is we want to fetch the latest news first and then only if we’re unable to do that because we’re offline or whatever, then we want to see if we might have an older version in our cache. So the cache first strategy would look something like this.

So first of all, we will open up the same cache that we had from before. We will then call cached match see if there’s something in our cache that matches this request. If there is we’ll return that, if not, we will fall back on the network, the network first strategy will look a little bit different, but should be pretty straightforward as well. So what we do here is we will open up the same cache but we’ll first try to see if we were able to fetch that from the network.

If we are able to fetch it from the network, we will put that version into the cache. So we’ll put a clone of it just because we’re only able to read a response once so that way we can put one version into the cache and then return the other one. If any of this fails. So if we’re unable to fetch the latest news, we’ll fall back on something that we have in our cache, so we’ll again call this cache that match and return that.

So, let’s go to our browser. Let’s refresh here, let’s look at the serviceworker here we have a serviceworker here, just registered. We can go into our cache storage here, verify that we’re caching stuff, not only those static assets that we have, but also some stuff from the network, and if we now go into the manifest file tab here, click on add to home screen. It will actually trigger the Add to Home screen logic.

We should always also be able to go to the serviceworker tab here and take our application offline and still be able to refresh and see that it’s working. So hopefully this gave you a good idea of what it’s like to turn an application into a progressive web application by adding that manifest file and adding that serviceworker now, normally, if you’re building an app for yourself, you probably don’t want to use this very low-level API That I just showed you there are libraries like workbox, that I’ll link in the show notes below that you can use to kind of simplify this a whole lot and gives you much more tools to do.

Things like manage your cache size and how many, how many images you want to cache or how long you want to keep something in the cache for all right. So thanks for reading, I hope you enjoyed it I’ll see you later.


 

Categories
Online Marketing

Intro to Web Push & Notifications

This diagram gives an overview on the client side. Your webpage interacts with service workers which in turn receive push events via the user agent, also known as the browser and on the backend.

You send messages from your application server to the push service, which then delivers them to the correct client. Let’s look at the notification API first, this allows developers to display notifications to the user. Before we can create a notification. We need to get permission from the user. This code will prompt the user permissions to show notifications. You can try this out from the browser console as you’ll see later, permission is requested automatically when subscribing to a push service.

So there’s no need to call this function when using just push notifications. Let’s take a look at some examples for configuring and displaying a notification from a service worker. We first check that permission has been granted. Then we call show notification on the service worker registration object and pass in the notification title. You can also try this out from the browser console. Try it on the new tab page now for push notifications.

You call show notification in the service worker in response to a push event. When a message arrives, we can specify an optional options: object to configure the notification. This is passed in as the second argument. In the show notification function, the body property is the body text displayed below the title icon? Is the image displayed at the top of notification? Vibrate is the vibration pattern for phones, in this case 100 milliseconds on 15 milliseconds off 130 seconds on so on, data is the arbitrary data we can retrieve in the service worker when the user interacts with the modification.

In this example, primarykey allows us to identify which notification was clicked when handling the interaction in the serviceworker. Let’s try that out. We can add action buttons to the notification that we can then handle each in a different way. Here’s what that looks like notification, interaction events are handled in the service worker tapping clicking or closing the notification. There are two notification interactions you can listen for in the service worker notification.

Close the notification close event only triggers when the notification is dismissed via a direct action on the notification. If the user dismisses all notifications, the event will not trigger, and this is done to save resources, notification, click. If the user clicks the notification or an action button in the notification, the notification click event is triggered. If the user clicked on an action, the action is attached to the event object of the notification click handler.

We can check which action was triggered and handle it separately. Now, let’s see how the two handlers work in a service worker. First notification close: we access the notification, object from the event object and we can get the data from the notification object. We might use the primary key property from the data to identify which notification was clicked in a notification click handler. We can determine what action button.

The user pressed by inspecting the action property on the event object. Note that each browser displays notification actions differently and some don’t display them at all to compensate. We put a default experience in this example in an else block after checking which action was clicked so that something will happen on a simple click of the notification. Now, let’s see how you send push messages from your server and handle incoming messages on your client web app.

Each browser manages push notifications through its own system called a push service when a user grants permission for push on your site, you subscribe them to the brow. Push service: this creates a subscription object that includes a public key to enable messages to be encrypted and an endpoint URL for the browser’s push service, which is unique for each user from your server. Send your push messages to this URL encrypted with the public key.

The push service sends the message to the right client. Now the service worker will be woken up to handle incoming push messages when a push event is fired, and this allows your app to react to push messages. For example, by displaying a notification using service worker registration show notification, your app doesn’t need to listen to or Pole for messages and the browser doesn’t even need to be open.

All the work is done under the hood as efficiently as possible by the browser and the operating system, and this is great for saving battery and CPU usage. Let’s go through that step by step in the apps main JavaScript call push manager subscribe on the serviceworker registration object, get the subscription object and convert it to jason, get the endpoint URL and public key and save this to your server, for example, by using a fetch Request send the message payload from your server to the endpoint URL encrypted with the public key.

The push message raises a push event in a serviceworker which we can handle in a push event handler in push event handler. We get the data from the message and display a notification. The push API allows users to subscribe to messages sent from your app server that are sent via the push service used by the browser and subscribing, of course, is done in the JavaScript. For the page, responding to push events, for example by displaying a notification, is done in the serviceworker, just to repeat subscribing to the push service and getting the subscription object happen in the JavaScript for the page.

First, we check if the user is already subscribed and update the page UI accordingly, if they are not subscribed, prompt them to subscribe, if they are already subscribed, update the server with the latest since that may have changed by the push service, since it was last used When the user grants permission for push on your site, you subscribe them to the browsers push service, as I said before, this creates a special subscription object that contains the endpoint URL for the push service, which is different for each browser, along with a public key.

We send the subscription object for this user to the server and save it now before you subscribe a user check if you already have a subscription object, if you don’t have the object again update the UI to prompt the user to enable push notifications, and if you Do have the subscription object, update your server database with the latest subscription object. The ready property of the service worker defines whether a service worker is ready to control the page or not.

It returns a promise which resolves to a serviceworker registration object. When the service worker becomes active, the get subscription function returns the subscription object or undefined. If it doesn’t exist, we need to perform this check every time. The user accesses our app because it is possible for subscription objects to change during their lifetime. This is the process of subscribing to the push service register, the service worker from the main page main jeaious.

This request goes to the user agent. The user agent returns the service worker registration, object, use the service worker at registration, object to access the push manager API and from that requests are subscribed to the push service. This request is passed on to the push service. The push service returns. The subscription object, which includes the endpoint URL and the public key, save the subscription object data to your server and send push messages from your server to the endpoint URL encrypted with the public key.

Like I said now before sending notifications, we must subscribe to a push service. We call push manager subscribe on the service worker registration object to subscribe and the resulting push subscription object includes all the information. The application needs to send a push me such an endpoint and encryption key needed for sending data each subscription is unique to a service worker. The end point for the subscription is a unique capability.

Url knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret or other applications might be able to send push messages to your application. Here’s an example of the subscription object. This is the object returned from the push service. When we call reg push manage, add subscribe. The subscription object has two parts.

The first part is an endpoint URL. The address on the push service to send messages to this includes an ID that enables the push service to send a message to the correct client and service worker. The second part of the subscription object is the keys property. The p25 6d H key is an elliptic curve, diffie-hellman ECD H public key for message. Encryption. The earth key is an authentication secret that your application server uses in authentication of its messages.

These keys are used by your application, server to encrypt and authenticate messages for the push subscription and, let’s see how the process of sending a message is done. The server generates a message encrypted with the public key and then sends it to the endpoint URL in the subscription object. The URL contains the address of the push service along with subscription ID, which allows the push service to identify the client to receive the message.

The message is received in the push service which routed to the right, client and the process of sending a push message from the server works. Like this. A back-end service on your server sends a push message to the push service using the endpoint URL from the subscription object. The message must be encrypted with the public key from the subscription object. The push service uses subscription IDs encoded in the endpoint URL, to send the message to the right user agent.

The push event is picked up by the service worker. The service worker gets the data from the message and displays a notification in this example. We’re using Google’s web push library for nodejs to send a push message from a node.Js server. The TTL value in the options specifies the time in seconds that the push service should keep trying to deliver the message now. This is important to set correctly some messages.

Have a short life some may be valid for several hours or more. We then pass in the subscription object. Payload and options object to send notification. You need a way to ensure secure communication between the user and your server and between your server and the push service and between the push service and the user. In other words, the user needs to be sure that messages are from the domain. They claim to be from and have not been tampered with by the push service you need to make sure the user is who they claim to be valid, was created to solve this problem.

This vapid identification information can be used by the push service to attribute requests that are made by the same application server to a single entity. This can be used to reduce the secrecy for push subscription URLs by being able to restrict subscriptions to a specific application server. An application server is further able to include additional information. The operator of a push service can use to contact the operator of the application server in order to use vapid, we need to generate a public/private key pair and subscribe to the push service using the public key.

The public key must be first converted from URL base64 to a you in 8 array. This is then passed into the application. Server key parameter in the subscribed method. The web push library, provides a method generate vapid keys, which generates the keys. This should be used once in the command line when push generate vapid, keys, Jason and the keys stored somewhere safe. We can use the web push library to send a message with the required vapid details.

We add a vapid details, object in the options parameter. That includes the parameter required for the request signing now. Let’s look at messages from the receiving end in the web. App on the client handling push, events happens in the surface worker, the service worker will be woken up to handle incoming push messages and a push event is fired. This allows your app to react to push messages, for example, by displaying a notification using service worker registration, show notification to display a push notification.

You listen for the push event in the service worker. You get the push message. Data from the push event object in this example, we simply convert the message: data to text The Wrap, show notification in a wait until to extend the lifetime of the push event. Until the show notification promise resolves, the push event will not be reported as successfully completed until the notification has displayed.

You can practice working with the notification and the push API by following the lab that accompanies this article, one small gotcha, don’t use private or incognito mode for this lab for security reasons, push notifications are not supported in private or incognito mode. You


 

Categories
Online Marketing

Payment Integration

This replaces the payment forms on a site with a much simpler experience on mobile devices. So let’s talk about paying for things on the web. This is a longer talk, so let me give you an idea of what’s coming up. First, we’ll talk about the user experience today and what could be better, we’ll look at the payment request, API twice.

First, to give you the big picture, then we’ll dive into the code. Finally, you’ll get the usual resources in lab. It’s no surprise, given the rise of mobile computing, that a majority of commercial traffic is coming from mobile devices, what is surprising is that 66 % of that mobile commerce is still happening on the web, even when people have native apps installed. Unfortunately, we also see a lot lower conversion rate on mobile web relative to desktop websites.

Mobile conversions are about one third of the desktop conversions. If you wonder why this is the answer is pretty simple. Checking out collecting payment from the user is still rather messy. People often give up while filling the checkout form some checkout forms have improved since the beginning of web Commerce. What hasn’t changed is you still have to manually input the same information credit card billing address and shipping address? Our first step to solving this problem is autofill, because autofill works on existing forms.

You don’t have to modify your site. Autofill just works to help users check out faster autofill alone increases conversion rates by 25 %. Autofill does a good job of identifying form fields, but it’s not perfect. If you want an even better experience, you can have the autocomplete attribute to your forms. In this example, we’ve annotated the credit card portion of a form using values such as CC name and CC.

Number autofill will know exactly where to place its information. If you want to learn more about autocomplete attributes search the web, using what WG autofill to find the specification, autofill gets rid of the manual nature of data entry and makes it much simpler for the user. The current checkout experience presents you with a form to fill out every time for users, though the ideal experience would be that, when it’s time to buy they just buy site should be able to focus on creating an amazing and engaging shopping experience without worrying about optimizing.

A long checkout form this is where the payment request API comes in, we’re going to look at it first from a user perspective and then look at the code. What if we could do away with the form using web payments when it’s time to pay the user? Just pays payment request is a simple JavaScript API that helps the browser collect payment information. Then it’s a simple one: tap checkout for the user and an easy way for a site to receive a payment.

With the payment request API, you can make the whole process much faster and simpler and since the browser is actually taking care of collecting payment information from the user, we go from end taps to one tap. Let’s take a quick look at the code flow here. First, the site initiates a payment request in this request. The website passes to the browser the parameters of the payment, for example, how much is being charged and the available forms of payment? Don’t worry about the details now we’ll come back in a few minutes and look at this in detail.

The browser then determines the intersection of payment methods from the site and what the user has. It then presents a selection UI where the user chooses their method of payment. You get the UI by calling show this displays a native UI over the browser within this UI, the user can change how to pay the delivery method and the delivery address. The payment method can be credit cards or one of the apps that’s installed on their device, such as Android pay and, finally, the user taps on pay.

Then the browser requests a response from the selected payment method. This might be an app on your device or going directly to a payment provider. The payment processor verifies the request by examining its details and then returns the response directly to the server and the website now has all the information it needs to process the payment. Is this safe? The API is more secure than forum based payments.

The new payments are based on modern cryptography. You don’t need to enter payment data that could be logged or observed at the point of entry. Autofill is safe from website access and is typically stored. An encrypted storage on the hard drive to prevent disclosure, even when the OS is compromised payment request, is not just a chrome only API. The API is currently under development in the w3c web payments working group.

The goal is to create a universal cross browser standard for any website to accept any form of payment so to review payment requests, eliminates manual and tedious entry by storing the user’s information securely in the browser. The browser passes, addresses and credit card details immediately and securely to the site, and since the browser is collecting payment information from the user, we go from end taps to one tap: you’ve seen how payment request works for the user.

Now, let’s go over the code in more detail. First, a quick review. The site initiates a payment request in this request. The website passes to the browser the parameters of the payment, including the price and the payment methods accepted. The browser determines the intersection of payment methods for the site and the user and presents a selection. Ui payment can be anything from a simple credit card payment to a payment application installed on the user’s device.

The browser requests a response from the selected payment method and returns the response directly to the merchant. There are multiple code samples for this on: Google, Chrome, github, dot, io. Let’s start writing some code. Step 1 is to tell payment requests. All the ways you can get paid. Step 2 is to define the details about the actual transaction cost items, currency, shipping options and so on.

Here’s an example of how you would define shipping options notice. The selected bit you can include this: if you have multiple options, the browser will tell you which one the user selects step 3 is to define what information you want. The API to collect. Take the three data structures you just created and pass them to the payment request. Constructor. You often do this when the user indicates they’re ready to pay, take the request and call it show method.

This returns a promise and opens the user interface. The UI shows the details of the purchase and collects payment information when the user approves the prom resolves with a payment response object. Next, you should check that the payment is valid. Send the information to your payment processor for processing the UI will show a spinner while the request takes place when a request comes back, call complete to close the UI.

The complete method tells the user agent that the user interaction is over. The payment response object contains everything needed to submit a payment for credit card payments. The response is standardized for non credit card payments such as Android pay. The response will be documented by the provider. There’s one loose end to tie up what happens if the user changes their shipping address or options.

This may change the total cost and in some cases, may change the shipping options. Payment requests can omit shipping address, change and shipping option change events. You should add event. Listeners for these and update the payment details. Accordingly, the sample code will show you how and that’s it. You can find a full set of resource links on this final slide. You may have noticed. I didn’t mention a lab, we’re just finishing it up at the time of filming, so check your lab notebook for a complete ecommerce example.


 

Categories
Online Marketing

Implementing the Web Payments API – Progressive Web App Training

Api is a w3c standard to eliminate payment forms for users and standardized payment collections for sites. It allows us to request payment and shipping information with a single API call.

This knows how to run Apple pay on iOS Safari and Google pay on Android. It’s not limited to those to any payment provider can write a plug-in. It’s not even restricted to one browser. It’s probably in the browser you’re using right now the browser simply acts as an intermediary collecting the information we need in a consistent way. Then returns a JSON object with the results that we can use to collect the payment.

If you have used a pay with Apple pay or pay with Google pay button in the browser, you already know what the experience will be, like developers previously used custom libraries to implement this, such as the Apple pay, API or the Google Wallet API, and if you Want to do that too great, but if you want to work with whatever payment system, the user has payment request. Is your friend, let’s take a quick look at the code flow and user experience? We want to buy this jacket, what happens when we tap buy now? This is an ordinary button with an ordinary event handler.

First, the site creates a payment request, object and populates it with some details. It typically has the price, a list of items being purchased and the available forms of payment. This is all invisible to the user. We need to trigger the payment user interface, you get the UI by calling payment request, dot, show this displays a native UI over the browser and returns a promise. The next few steps are all happening inside this promise.

The first screen is a summary of the information supplied by the app tapping on an item opens it the EPI stores, addresses and payment options securely. In this example, Larry can select his shipping address with one tap edit. The address or add another need to change. The shipping option no problem: it’s just kappa way note that changing this option may change the total price. The payment request api can handle this with a little help from your app notice, the multiple payment options, the api also handles country, specific payment methods and, finally, the user taps on pay.

At this point, the browser runs the selected payment service. This might be an app on your device or going across the network to a payment provider. The completed payment returns a special token that you can send to your server. The server has ways of verifying this token. Is this safe? The api is more secure than form based payments. The new payment instruments are based on modern cryptography. You don’t need to enter payment data that can be logged or observed at the point of entry, so to review payment requests, eliminates manual and tedious entry by storing the user’s information securely in the browser.

It works across browsers across OS platforms and can work with any payment service that wants to write just a little code now that you’ve seen how payment request works for the user, let me show you how to code it remember that the payment UI contains multiple sections. We need to populate these sections before making the request. The request needs at least three data structures, the payment options, the order, details and shipping options so we’ll create those then generate a payment request.

We will call show and get back a promise that resolves when it’s time to contact the payment processor, finally notice that we may want to or three event handlers. These are called while the UI is visible and can trigger updates when the user changes addresses or shipping options. Let’s walk through the steps in the UI and the corresponding code. First, the user taps by now. So we want to set up a payment request.

Remember that we need some data structures before we can create the request. The payment methods lists all the payment services that your site understands. It’s an array of payment method, objects and each method may have its own specific properties here. We’re listing the basic credit card method and Google pay note that I’m leaving out the details of the Google pay object as it’s pretty involved.

We want the user to know what they’re buying. This includes the core details of the transaction, how much money? What currency? And what list items you want displayed? Keep the line items fairly high level. It isn’t meant to be used as an itemized receipt. If you want more than one shipping option, you can define this structure notice, it’s a property on the transaction details. If you have multiple options include a selected bit, the browser will highlight the selected option and fire an event when it changes.

Now you can define what information you want from the API by default. Payment requests will only return the payment info if the user is logged. In you may have the rest of their information. If you need more these options, let you collect what you need. Take the data structures, you’ve just created and pass them to the payment request constructor. This should happen in response to a button tap or other user initiated action.

Now so far the screen hasn’t changed. We need to trigger the UI, take the payment request and call the show method. This returns a promise and opens the user interface notice. There’s a big block of code. After this, we still have a couple of steps until we’re done. The UI shows the details of the purchase and collects payment information when the user approves the promise resolves with a payment response object.

The payment response object contains everything needed to submit a payment for credit card payments. The response is standardized for non credit card payments such as Google pay. The response will be documented by the provider. Next, you should check that the payment is valid. Send the information to your payment processor for processing the UI will show a spinner while the request takes place. Okay.

So how do we remove the payment UI after we click payment? Even if it fails call payment response, not complete. You can include a message to the user. This tells the browser that the payment is complete and allows the app to notify the user of the result. Now, there’s one loose end to tie up what happens if the user changes their shipping address or options. This may change a total cost and, in some cases, may change a shipping options.

Payment requests can omit shipping, address, change, shipping, option, change and payment method change events. You should have event listeners for these and update details accordingly. Remember we’re making the update in the middle of a promise, just as we do installing the Service Worker, so we use a similar bit of code. We get the event and call update with on it. This takes a promise that resolves to a new transaction details record.

It’s not all that different from calling cache at all from the service workers install event that also returns its result via the event. The get new info method is something that you would write. It takes some data from the request and builds a new transaction details. Object. Here’s a reminder of what goes in the transaction details. Your code probably needs to copy from the old object to a new one.

We resolve the promise with the new details, update with then updates the payment request and the screen, and that’s it. You now have a seamless, easy to use checkout experience now that was a bit of a long example, but most of it is boilerplate check out the payment request. Samples at Google, Chrome, github, io, remember the process for easier payments starts with autofill. If you want more payment request, is there to help? You can also check out specific libraries for Apple pay, Google pay, Samsung pay and others they put up a pay with button on the screen.

They usually fall back to the payment request interface, but they may be an easier option for your users. The only way to know is to try them for yourself thanks for hanging in there through web payments. This is one of the most complex parts of building a PWA, yet it’s really satisfying and could be great for business. Take care and I’ll see you again soon.


 

Categories
Online Marketing

New Techniques for Responsive Design

We have different devices. Different needs even different data requirements, and this is at the core of the PWA attitude to building for the web. We need layouts and content that work across devices if your site doesn’t adapt to the user’s device, you break the illusion and lose trust.

These quotes are from Brad, Frost and Liza danger. Gardner. You should check out that blog post about responsive design, which are linked to from the course materials as Liza says, manage risk focus on content. You know you can make virtually any site usable simply by sizing elements and content correctly. The golden rule for great progressive web app content is not to let content inadvertently overflow horizontally, especially on mobile.

That sounds basic, but lots of sites break this rule by making images inputs and other large elements on the page with fixed sizes. Using relative measurement units and RAM percentages will reduce the severity of this issue. Adding a meta viewport tag will also solve a lot of problems. This tells the browser the size of the virtual viewport on which it renders a web page without setting the viewport meta tag correctly, most browsers scaled down the page to fit a virtual 980 pixel wide viewport.

I’ve seen some great examples of this in action on w3schools, we’ll give you the URLs for that in the course materials. With this article, the initial scale value sets the zoom default. For this page, don’t set a maximum value that will make it impossible for users to zoom and that’s a big problem for accessibility. One other thing you should be aware of the viewport meta tag will mess up the layout for fixed-width sites.

The Mater viewport tag is designed to work with responsive layout. If you use it in a fixed sized layout, it will break things until you convert the site to a responsive, lay out trade document.Documentelement client to see how the viewport meta tag affects the virtual viewport. Here’s another simple technique: this solves many layout problems, you’re setting the preferred size and the maximum size and works for article and audio too so yeah.

You might think that relative sizing would fix everything, in fact, for a while back in the day, some of us thought that relative sizing could solve everything we layout. We had, you know liquid layout, maybe even text could be relatively sized, but relative sizing isn’t enough simplistic. Relative sizing, like this a diagram, means that you have content areas that are too big on desktop and to smaller mobile.

This is why media queries were invented. It’s a simple concept, use different CSS for different sized viewport based on width. That doesn’t just mean making the same layout for every device on a phone. You might want a single column layout, a two column layout on a tablet. Maybe three columns for desktop and so on. You can use media queries to select different layouts depending on the viewport size, here’s a single column layout on mobile to column, on tablet and three columns for desktop.

So do you think about devices, and you might think you could get away with this? Ask yourself what could go wrong with this approach? What about new devices new viewport sizes? What about changing window sizes on desktop we’ll come back to this later now? Is that all there is, of course not. There is a better way go back to our original exercise. Remember content is king devices, keep changing and device, viewports are getting bigger and smaller, not to mention pixel density, pixel, shape, display quality and so on.

Don’t force your designers and developers to make a change every time a new device appears start. The design process with the smallest form factor then add the major breakpoints for the form factors that you work with phone tablets, laptops and widescreen devices. You can then create minor breakpoints to handle specific changes to elements that don’t affect all elements. The final detail to keep in mind is to optimize the content for reading, ideally keep the width of your content to 70 to 80 characters wider than that value makes content hard to read.

Now that doesn’t mean you stop thinking about devices and device classes. You might want one column for phones, two columns for tablets, three columns for desktop, like we’re saying or whatever you can find out more about these recommendations on web fundamentals. Now remember the earlier media queries example in the mobile first world of PWS. We need to turn that around make small viewports the default.

Look at the example here. By the way, there is no fixed rule about whether or not to include media queries, inline or use a separate file. Also, you might want to consider using m’s or REMS for units here, but I won’t go into that now. You’ll also do responsive layout in JavaScript. If you like, this is a simple way to do. Conditional content match media is well supported and there are polyfills. Calc is really useful in responsive design, where you want to use a combination of fixed widths and percentages.

In this example, we have two thumbnail images: side by side: 50 %, the width of the parent element with a 10 pixel margin between them, no matter what size. The viewport responsive design is about more than just changing layouts, as well as changing layouts. You might actually also want to manipulate content, depending on the viewport size and device type, for example, on a phone you might want to make sure page content is visible when the user goes to your home page, so you might opt for a hamburger menu for navigation And put banner ads lower on the page.

Also, if need be, you can just get rid of stuff on desktop. Your users will want full functionality, but not on mobile right wrong. Don’t guess your users needs based on viewport size, plan, content and functionality carefully and don’t assume users want less content or functionality on phones than desktop, for example. Again, this is a crucial part of the PWA attitude. Understand your users, don’t second-guess them.

Data-Driven design, design, content, layouts and transaction processes, so users can get to what they want as quickly as possible. Our data shows that every step to get to content loses 20 % of users rather than removing content. A more sensible option can be to choose different content. Now for images this is called art direction, choosing different images or different image crops and I’ll show an example of this later.

You might even want to provide different text for different viewports such as shorter headlines, but yeah be careful again not to assume that mobile users want less content for article. The general rule is to use a smaller resolution for smaller viewports. This can result in massive reductions in bite, size, playback performance and proven sand, also reduced streaming cost. The best way to do this is with adaptive streaming or HLS, not just media queries and yeah.

You can find out more about that more about adaptive streaming in the course materials. But just to reiterate, the key point here is that when you’re delivering article to mobile, don’t use resolutions larger than you need and talking about article content, don’t forget to caption articles using the track element. It’s really easy. Let’s take a look at the relatively new technique for creating responsive layouts, CSS flexbox provides flexible sizing and alignment element reordering and better performance than floats.

Css flexbox is well supported and we strongly recommend it easy centering is the holy grail of CSS. Take a look at the code here. It is incredibly simple. I still find it slightly thrilling by the way the materials that accompany this article have links to lots of flexbox examples, including this one. Let’s look at the CSS for the examples here. This uses CSS flexbox for three different layouts depending on the viewport width.

Let’s start with the defaults for smaller viewports, remember, mobile-first, the container is declared to use CSS flex. The flex flow property means child elements can wrap. Rather than being squashed onto the same line. You can also use inline flex, that’s shorthand for flex direction and flex wrap properties. The default is ro, no rap 100 % width for each div in the container add a different layout for slightly larger viewport and different again, once the width hits 800 pixels.

The container is now a fixed width and centered horizontally using margins. Let’s take a look at the example here. Once again, this uses CSS flexbox for three different layouts, depending on the viewport width and again, let’s start with the defaults for smaller viewports. For view puts over 600 pixels in width. The order is changed on the smaller viewports. We wanted to give child 1 full width, but for a slightly larger viewport, we can put it next to child 2.

I could go on anyway, to other properties. I’d like to draw your attention to justify content, how items are packed and aligned items how items are aligned. Css grid is in some ways related to the grid system concept, familiar to graphic designers. A page is thought of in terms of lines tracks between lines, cells and areas. Css grid is coming, and it’s already behind a flag in Chrome and Firefox you’ll find more information in the resources for this article.

The lab exercises that accompany this article will help you get started with media queries, breakpoints grids and with flexbox


 

Categories
Online Marketing

Introduction to Service Workers

You’Ll learn what a service worker is and what it can do for your apps. A service worker is a client-side programmable proxy between your web app and the outside world. It gives you fine control over network requests. For example, you can control the caching behavior of requests for your site HTML and treat them differently than requests for your site’s images.

Service workers also enable you to handle push messaging now. Service workers are a type of web worker, an object that execute the script separately from the main browser thread. Service workers run independent of the application they are associated with and can receive messages when not active either, because your application is in the background or not open or the browser is closed. The primary uses for a service workers are to act as a caching agent to handle network requests and to store content for offline use and, secondly, to handle push messaging.

The service worker becomes idle when not in use and restarts when it’s next needed. Now, if there is information that you need to persist and reuse a course restarts, then service workers can work with indexdb databases. Service workers are promised based now we cover this more in other materials, but at a high level a promise is an object. These are the kind of placeholder for the eventual results of a deferred and possibly asynchronous computation service workers also depend on to api’s to work effectively fetch a standard way to retrieve content from the network and cache a persistent content storage for application data.

This cache is persistent and independent from the browser, cache or network status now because of the power of a service worker and to prevent man-in-the-middle attacks where third parties track the content of your users. Communication with the server service workers are only available on secure origins served through TLS using the HTTP protocol will test service workers using local host, which is exempt from this policy.

By the way, if you’re hosting code on github, you can use github pages to serve content. Their provision with SSL by default services, like let’s encrypt, allow you to procure SSL certificates for free to install on your server Service Worker, enabled applications to control network requests, cache those requests to improve performance and to provide offline access to cached content. But this is just the tip of the iceberg.

We will explore some things you can do with service workers and related api’s caching. Assets for your application will make the content load faster under a variety of Network conditions. Two specific types of caching behavior suitable for use are available through service workers. The first type of caching is the precache assets during installation. If you have assets, HTML, CSS, JavaScript images so on, and these are shared across your application.

You can cache them when you first install the serviceworker when your web app is first opened. This technique is at the core of application. Shell architecture now note that using this technique does not preclude regular dynamic caching, you can combine the pre cache with dynamic caching. The second type of caching is to provide a fallback for offline access using the fetch API inside a serviceworker.

We can fetch request and then modify the response with content other than the object requested use this technique to provide alternative resources in case the requested resources are not available in cache, and the network is unreachable. Service workers can also act as a base for advanced features. Service workers are designed to work as the starting point for features that make web applications work like native apps, and some of these features are blog messaging API, which allows web workers and service workers to communicate with each other and with the host application examples of this Api include new content notifications and updates that require user interaction.

The notifications API is a way to integrate push notifications from your application to the operating system native notification system. The push API enables push services to send push messages to an application service can send messages at any time, even when the application or the browser is not running. Push messages are delivered to a service worker which can use the information in the message to update local state or display a notification to the user background.

Sync lets you defer actions until the user has stable connectivity, and this is really useful for ensuring that whatever the user wants to send is actually sent. This API also allows servers to push periodic updates to the app, so the app can update when its next on line. Every service worker goes through three steps in its lifecycle, registration, installation and activation to install the service worker.

You need to register it in your main JavaScript code. Registration tells the browser where your service worker is where it’s located and to start installing it. In the background, for example, you could include a script tag in your site’s index.Html file or whatever file you use. Is your applications entry point with code similar to the ones shown here? This code starts by checking for browser support by attempting to find Service Worker as a property in the navigator object.

The service worker is then registered with navigator dot Service Worker dot register, which returns a promise that resolves when the service worker has been successfully registered. The scope of the service worker is then logged with registration, dot scope. You can attempt to register a service worker every time, the page loads and the browser will only complete the registration. If the service worker is new or has been updated, the scope of the Service Worker determines from which path the service worker will intercept requests.

The default scope is the path to the Service Worker file and extends to all directories below it. So if the Service Worker script, for example, Service Worker dot gif, is located in the root directory, the Service Worker will control requests from all files at best domain. You can also set an arbitrary scope by passing in an additional parameter when registering in this example. We’Re setting the scope of the Service Worker to slash app, which means the service worker will control requests from pages like slap slap, slash, lower and slash out, slash, lower slash low directories like that, but not from pages like slash, app or slash, which are higher a Service worker cannot have a scope above its own path.

This is in your service worker file, service worker, dot, j s now thinking about installation. Once the browser registers a service worker, the install event can occur. This event will trigger if the browser considers the service worker to be new either, because this is the first service worker encountered for this page or because there is a bite difference between the current service worker and the previously installed one.

We can add an install event handler to perform actions during the install event. The install event is a good time to do stuff, like caching, the apps your static assets using the cache API. If this is the first encounter with the service worker, for this page, the service worker will install and if successful, transition to the activation stage upon success once activated, the service worker will control all pages that load within its scope and intercept corresponding network requests.

However, the pages in your app that are open will not be under the serviceworkers scope, since the serviceworker was not loaded when the page is opened to put currently open pages under serviceworker control, you must reload the page or pages. Until then, requests from this page will bypass the serviceworker and operate just like they normally would service workers maintain control as long as there are pages open that are dependent on that specific version.

This ensures that only one version of the serviceworker is running at any given time. If a new serviceworker is installed on a page with an existing serviceworker, the new serviceworker will not take over until the existing serviceworker is removed. Old service workers will become redundant and be deleted once all pages. Using it are closed. This will activate the new serviceworker and allow it to take over refreshing.

The page is not sufficient to transfer control to a new serviceworker, because there won’t be a time when the old serviceworker is not in use. The activation event is a good time to clean up stale data from existing caches. The application note that activation of a new serviceworker can be forced programmatically, with self dot skips waiting service workers are event-driven installation and activation events, fire off corresponding events to which the serviceworker can respond.

The install event is when you should prepare your serviceworker for use. For example, by creating a cache and adding assets to it, the activate event is a good time to clean up old caches and anything else associated with a previous version of your serviceworker. The serviceworker can receive information from other scripts through message. Events. There are also functional events, such as fetch push and think that the serviceworker can respond to to examine service workers navigate to the serviceworker section in your browsers, developer tools, different browsers, put the tools in different places, check debugging service workers in browsers for instructions for Chrome, Firefox and opera, a fetch event is fired every time a resource is requested.

In this example, we listen to the fetch event and instead of going to the network, returned the requested resource from the cache assuming it is. Their service workers can use background sync here. We start by registering the service worker and once the service worker is ready, we register a sync event with the tag foo. The service worker can listen to sync events. This example listens for the sync event, tagged foo in the previous slide.

Do something should return a promise indicating the success or failure of whatever it’s trying to do if it fulfills the sync is complete. If it fails, another sync will be scheduled to retry retry syncs also wait for connectivity and employ an exponential back-off. The service worker can listen for push events, push events are initiated by your back-end servers through a browsers push service. This example shows a notification when the push event is received.

The options object is used to customize the notification. The notification could contain the data that was pushed from the service service workers can be tested and debug in the supporting browsers, developer tools. Screenshot here shows the chrome dev tools application panel. There are lots of great resources to help you get started and find out more access them from the materials that accompany this article.

In the lab materials that accompany this article, you can practice working with service workers and learn more about intercepting Network requests.


Website management packages are important for any business these days. Check out the video from Allshouse Designs to see what can be done for your company and yes, for how much. 

 

Categories
Online Marketing

Intro to Web Push & Notifications

This diagram gives an overview on the client side. Your webpage interacts with service workers which in turn receive push events via the user agent, also known as the browser and on the backend.

You send messages from your application server to the push service, which then delivers them to the correct client. Let’S look at the notification API first, this allows developers to display notifications to the user. Before we can create a notification. We need to get permission from the user. This code will prompt the user permissions to show notifications. You can try this out from the browser console as you’ll see later, permission is requested automatically when subscribing to a push service.

So there’s no need to call this function when using just push notifications. Let’S take a look at some examples for configuring and displaying a notification from a service worker. We first check that permission has been granted. Then we call show notification on the service worker registration object and pass in the notification title. You can also try this out from the browser console. Try it on the new tab page now for push notifications.

You call show notification in the service worker in response to a push event. When a message arrives, we can specify an optional options: object to configure the notification. This is passed in as the second argument. In the show notification function, the body property is the body text displayed below the title icon? Is the image displayed at the top of notification? Vibrate is the vibration pattern for phones, in this case 100 milliseconds on 15 milliseconds off 130 seconds on so on, data is the arbitrary data we can retrieve in the service worker when the user interacts with the modification.

In this example, primarykey allows us to identify which notification was clicked when handling the interaction in the serviceworker. Let’S try that out. We can add action buttons to the notification that we can then handle each in a different way. Here’S what that looks like notification, interaction events are handled in the service worker tapping clicking or closing the notification. There are two notification interactions you can listen for in the service worker notification.

Close the notification close event only triggers when the notification is dismissed via a direct action on the notification. If the user dismisses all notifications, the event will not trigger, and this is done to save resources, notification, click. If the user clicks the notification or an action button in the notification, the notification click event is triggered. If the user clicked on an action, the action is attached to the event object of the notification click handler.

We can check which action was triggered and handle it separately. Now, let’s see how the two handlers work in a service worker. First notification close: we access the notification, object from the event object and we can get the data from the notification object. We might use the primary key property from the data to identify which notification was clicked in a notification click handler. We can determine what action button.

The user pressed by inspecting the action property on the event object. Note that each browser displays notification actions differently and some don’t display them at all to compensate. We put a default experience in this example in an else block after checking which action was clicked so that something will happen on a simple click of the notification. Now, let’s see how you send push messages from your server and handle incoming messages on your client web app.

Each browser manages push notifications through its own system called a push service when a user grants permission for push on your site, you subscribe them to the brow. Push service: this creates a subscription object that includes a public key to enable messages to be encrypted and an endpoint URL for the browser’s push service, which is unique for each user from your server. Send your push messages to this URL encrypted with the public key.

The push service sends the message to the right client. Now the service worker will be woken up to handle incoming push messages when a push event is fired, and this allows your app to react to push messages. For example, by displaying a notification using service worker registration show notification, your app doesn’t need to listen to or Pole for messages and the browser doesn’t even need to be open.

All the work is done under the hood as efficiently as possible by the browser and the operating system, and this is great for saving battery and CPU usage. Let’S go through that step by step in the apps main JavaScript call push manager subscribe on the serviceworker registration object, get the subscription object and convert it to jason, get the endpoint URL and public key and save this to your server, for example, by using a fetch Request send the message payload from your server to the endpoint URL encrypted with the public key.

The push message raises a push event in a serviceworker which we can handle in a push event handler in push event handler. We get the data from the message and display a notification. The push API allows users to subscribe to messages sent from your app server that are sent via the push service used by the browser and subscribing, of course, is done in the JavaScript. For the page, responding to push events, for example by displaying a notification, is done in the serviceworker, just to repeat subscribing to the push service and getting the subscription object happen in the JavaScript for the page.

First, we check if the user is already subscribed and update the page UI accordingly, if they are not subscribed, prompt them to subscribe, if they are already subscribed, update the server with the latest since that may have changed by the push service, since it was last used When the user grants permission for push on your site, you subscribe them to the browsers push service, as I said before, this creates a special subscription object that contains the endpoint URL for the push service, which is different for each browser, along with a public key.

We send the subscription object for this user to the server and save it now before you subscribe a user check if you already have a subscription object, if you don’t have the object again update the UI to prompt the user to enable push notifications, and if you Do have the subscription object, update your server database with the latest subscription object. The ready property of the service worker defines whether a service worker is ready to control the page or not.

It returns a promise which resolves to a serviceworker registration object. When the service worker becomes active, the get subscription function returns the subscription object or undefined. If it doesn’t exist, we need to perform this check every time. The user accesses our app because it is possible for subscription objects to change during their lifetime. This is the process of subscribing to the push service register, the service worker from the main page main jeaious.

This request goes to the user agent. The user agent returns the service worker registration, object, use the service worker at registration, object to access the push manager API and from that requests are subscribed to the push service. This request is passed on to the push service. The push service returns. The subscription object, which includes the endpoint URL and the public key, save the subscription object data to your server and send push messages from your server to the endpoint URL encrypted with the public key.

Like I said now before sending notifications, we must subscribe to a push service. We call push manager subscribe on the service worker registration object to subscribe and the resulting push subscription object includes all the information. The application needs to send a push me such an endpoint and encryption key needed for sending data each subscription is unique to a service worker. The end point for the subscription is a unique capability.

Url knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret or other applications might be able to send push messages to your application. Here’S an example of the subscription object. This is the object returned from the push service. When we call reg push manage, add subscribe. The subscription object has two parts.

The first part is an endpoint URL. The address on the push service to send messages to this includes an ID that enables the push service to send a message to the correct client and service worker. The second part of the subscription object is the keys property. The p25 6d H key is an elliptic curve, diffie-hellman ECD H public key for message. Encryption. The earth key is an authentication secret that your application server uses in authentication of its messages.

These keys are used by your application, server to encrypt and authenticate messages for the push subscription and, let’s see how the process of sending a message is done. The server generates a message encrypted with the public key and then sends it to the endpoint URL in the subscription object. The URL contains the address of the push service along with subscription ID, which allows the push service to identify the client to receive the message.

The message is received in the push service which routed to the right, client and the process of sending a push message from the server works. Like this. A back-end service on your server sends a push message to the push service using the endpoint URL from the subscription object. The message must be encrypted with the public key from the subscription object. The push service uses subscription IDs encoded in the endpoint URL, to send the message to the right user agent.

The push event is picked up by the service worker. The service worker gets the data from the message and displays a notification in this example. We’Re using Google’s web push library for nodejs to send a push message from a node.Js server. The TTL value in the options specifies the time in seconds that the push service should keep trying to deliver the message now. This is important to set correctly some messages.

Have a short life some may be valid for several hours or more. We then pass in the subscription object. Payload and options object to send notification. You need a way to ensure secure communication between the user and your server and between your server and the push service and between the push service and the user. In other words, the user needs to be sure that messages are from the domain. They claim to be from and have not been tampered with by the push service you need to make sure the user is who they claim to be valid, was created to solve this problem.

This vapid identification information can be used by the push service to attribute requests that are made by the same application server to a single entity. This can be used to reduce the secrecy for push subscription URLs by being able to restrict subscriptions to a specific application server. An application server is further able to include additional information. The operator of a push service can use to contact the operator of the application server in order to use vapid, we need to generate a public/private key pair and subscribe to the push service using the public key.

The public key must be first converted from URL base64 to a you in 8 array. This is then passed into the application. Server key parameter in the subscribed method. The web push library, provides a method generate vapid keys, which generates the keys. This should be used once in the command line when push generate vapid, keys, Jason and the keys stored somewhere safe. We can use the web push library to send a message with the required vapid details.

We add a vapid details, object in the options parameter. That includes the parameter required for the request signing now. Let’S look at messages from the receiving end in the web. App on the client handling push, events happens in the surface worker, the service worker will be woken up to handle incoming push messages and a push event is fired. This allows your app to react to push messages, for example, by displaying a notification using service worker registration, show notification to display a push notification.

You listen for the push event in the service worker. You get the push message. Data from the push event object in this example, we simply convert the message: data to text The Wrap, show notification in a wait until to extend the lifetime of the push event. Until the show notification promise resolves, the push event will not be reported as successfully completed until the notification has displayed.

You can practice working with the notification and the push API by following the lab that accompanies this article, one small gotcha, don’t use private or incognito mode for this lab for security reasons, push notifications are not supported in private or incognito mode. You


Website management packages are important for any business these days. Check out the video from Allshouse Designs to see what can be done for your company and yes, for how much.