If a Web Developer Could Build Mobile Apps...

Without going through App/Play Store!

I'm Neeraj

    GeekyAnts

We are the ones behind

NativeBase

BuilderX

/@neerajsingh47

NativeBase

A set of UI components to ease React Native development.

7,200+ Github stars.

8% of React Native downloads.

Progressive Web Apps

What is PWA?

A mixture of mobile and web app

Native Apps

Designed in a native language for a single OS

Takes advantage of the device hardware

High performance

Modify system settings

Telephony features

Slower Iterations

Traditional Web Apps

Delivered in real time

Built using standard HTML, CSS, and JavaScript.

Limited access to device's features

Can't add direct shortcut to mobile home screen

Doesn't support offline features

Faster Iterations

PWA

Low friction of distribution

Discoverability

Universal access

System access

iOS support in progress

Discoverability

Native Apps are only available via stores.

PWAs don't have the same restrictions.

 App Icon on HomeScreen

No Custom URL!

<link rel="manifest" href="/manifest.json">
{
    "short_name": "PWAR",
    "name": "PWAR",
    "icons": [
        {
            "src": "favicon.ico",
            "sizes": "192x192",
            "type": "image.png",
        }
    ],
    "start_url": "./index.html",
    "display": "standalone",
    "theme_color": "#000000",
    "background_color": "#ffffff",
}

Manifest.json

Push Notifications

Service Workers

What are they?

A script that your browser runs in the background.

Completely separate from the web page.

Provides features that don't need a web page or user interaction (Push notification and background sync)

if ('serviceWorker' in navigator) {
    // Register a service worker hosted at the root of the 
    // site using the default scope.
    navigator.serviceWorker.register('/sw/js').then(function(registration) {
        console.log('Service worker registration succeeded:', registration);
    }).catch(function(error) {
        console.log('Service worker registration failed:', error);
    });
} else {
    console.log('Service workers are not supported.');
}

Registering a Service Worker

How To Push Notification?

Server Side

1. Generate data to send to user.

2. Encrypt the data with the user public key.

3. Send to data to the endpoint URL with a           payload of encrypted data.

Sending Push Notifications Through Server

Voluntary Application Server Identification for Web Push

VAPID

VAPID uses JSON Web Tokens to carry information.

Core of VAPID is called claim.

Claim is a JSON object containing several common fields.

How to VAPID?

1. Your application server creates a public/private          key pair. Public key is given to your web app.

2. When user elects to receive pushes, add the              public key to the subscribe() call's options object.

3. When the app's server sends a push message,            include a signed JSON web token along with              the public key.

An unauthorized push service is exposed to a greater risk of DOS attack.

Any app server in possession of the endpoint can send messages to your user.

No way for push service to contact the developer if there are problems.

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

const vapidKeys = webpush.generateVAPIDKeys();

webpush.setGCMAPIKey('<Your GCM API Key Here>');
webpush.setVapidDetails(
    'mailto:example@yourdomain.org',
    vapidKeys.publicKey,
    vapidKeys.privateKey,
);

Web Push

const pushSubscription = {
    endpoint: '.....',
    keys: {
        auth: '.....',
        p256dh: '.....',
    }
);

webpush.sendNotification(pushSubscription, 'Your Push Payload Text');

Sending Push Notification

Client Side

1. Subscribe to the push service.

 

2. Send the subscription object to the server.

 

Push messaging provides a simple and effective way to re-engage with users.

Notification.requestPermission(function(status) {
    console.log('Notification permission status: ', status);
});

Push Notification Listener

self.addEventListener('push', function(event) {
    console.log('[Service Worker] Push Received.');
    console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
    
    const title = 'Push Codelab':
    const options = {
        body: 'Yay it works!',
        icon: 'images/icons.png',
        badge: 'images/badge.png',
    };
    event.waitUntil(self.registration.showNotification{title, options});
});

Offline Capabilities

What happens to your app when there is no internet connection?

When should you update your App?

It is up to the developer to display notifications on the web app to inform the user that a new update is available

App Updates

React + PWA

React can render in the back-end using React.renderToString()

Async import

import React, {Component} from 'react';

export default class AsyncComponent extends Component {
    state = {
        component: null
    }
    componentDidMount() {
        // load component on mount

        import('./LineChart').then((LineChartComponent) => {
            this.setState({
                component: LineChartComponent
            });
        }).catch((error) => {
            console.warn('Error while loading component');
        })
    }
    render() {
        if(this.state.component) {
            return <this.state.component />
        }
        return (<div>Loading</div>);
    }
}

Tools

Lighthouse

Workbox

Lighthouse

Workbox

A collection of libraries and build tools that makes it easy to store your website's file locally, on your user's devices.

workbox.precache([
    {
        "url": "index.html",
        "revision": "b3d78920c49d0c927050682c99df3",
    }
]);

Workbox Caching Strategies

Cache only

Cache first, falling back to network

Cache with network update

Network only

Network first, falling back to cache

const workboxSW = new WorkboxSW();

const networkFirst = workboxSW.strategies.networkFirst();

workboxSW.router.registerRouter('/schedule', networkFirst);

PWA is the next step in web development.

Try it out and be ready for the Future!

Thank you!

/@neerajsingh47

ReactFoo Pune

By neerajsingh47

ReactFoo Pune

  • 486