[email protected]
Facebook
Gorjeo
LinkedIn
GitHub
  • Blog
  • GitHub
  • Currículum
    • LinkedIn
    • StackOverflow
  • 🙈
    • 🇺🇸 Inglés
    • 🇪🇸 Español
    • 🇫🇷 Francés
    • 🇧🇷 Português

JFA PWA Toolkit

abril 5, 2019LibreriasNo hay comentariosjfadev

Con este toolkit se puede integrar fácilmente las características más notables de un PWA. Esta solución se integra fácilmente en proyectos antiguos con jQuery o en nuevos frameworks Javascript. Este proyecto está en desarrollo. No dude en probarlo y enviar sus Issus y Pull Resquests en Github.

🚀 Descubre el repositorio en GitHub.
📱 Prueba la Demo (repositorio de la demo).

Caracteristicas

  • Web App Manifest
  • Estructura de ficheros de iconos
  • Precaching
  • Estrategias de almacenamiento en caché
  • Notificaciones Push

Documentación

  • Documentación
  • Referencia de la API

Empieza con un Ejemplo

Importante: Para que este ejemplo funcione a la perfección, debe ser utilizado en localhost o en un dominio https y el index.html debe encontrarse en la raíz del sitio..

Clone jfa-pwa-toolkit desde el repositorio de Github y crear un archivo index.html y un offline.html archivo.

1
2
3
4
5
$ git clone --branch v1.0-beta git@github.com:jfadev/jfa-pwa-toolkit.git
$ mv jfa-pwa-toolkit my-pwa
$ cd my-pwa/
$ touch index.html
$ touch offline.html

Sencillo index.html skeleton (esqueleto completo en la documentación).
Pega este esqueleto en su index.html archivo.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Theme color -->
    <meta name="theme-color" content="#000" />
    <!-- PWA Manifest -->
    <link rel="manifest" href="/pwa/manifest.json"></link>
    <!-- Favicon -->
    <link rel="icon" type="image/png" href="/pwa/icons/chrome/chrome-favicon-16-16.png">
    <!-- Icons -->
    <!-- Splash Screen -->
    <title>JFA PWA Toolkit Example</title>
</head>
<body>
    <!-- Load JFA PWA Toolkit Configs -->
    <script type="text/javascript" src="/pwa/config.js"></script>
    <!-- Load JFA PWA Toolkit Lib -->
    <script type="text/javascript" src="/pwa/pwa.js"></script>
    <!-- Register principal Service Worker -->
    <script type="text/javascript">
        PWA.ServiceWorker.register();
    </script>
</body>
</html>

Pegar, por ejemplo, este simple html en su offline.html archivo.

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html lang="en-us">
<head>
    <title>OFFLINE - JFA PWA Toolkit Example</title>
</head>
<body>
    <p>No Internet connection!</p>
</body>
</html>

Ejemplo de contenido del manifest.json. Puede usar app.webmanifest en lugar de manifest.json si lo prefiere.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
    "dir": "ltr",
    "lang": "en-us",
    "name": "Your App Name",
    "scope": "/",
    "display": "standalone",
    "start_url": "/",
    "short_name": "Your App Short Name",
    "description": "Your App Description.",
    "orientation": "any",
    "theme_color": "#000",
    "background_color": "#000",
    "related_applications": [],
    "prefer_related_applications": false,
    "icons": [{
            "src": "/pwa/icons/windows10/Square71x71Logo.scale-400.png",
            "sizes": "284x284"
        },
    ]
}

Ejemplo de un simple config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const PWA_CONFIG = {
    app: {
        name: 'your-app-name',
        version: 'v1'
    },
    sw: {
        filepath: '/sw.js',
        offline_route: '/offline.html'
    },
    cache: {
        images: {
            active: true,
            maxentries: 50,
            maxageseconds: 24 * 60 * 60
        },
        statics: {
            active: true,
            maxentries: 50,
            maxageseconds: 24 * 60 * 60
        },
        fonts: {
            active: true,
            maxentries: 50,
            maxageseconds: 24 * 60 * 60
        },
        routes: {
            networkfirst: {
                active: true,
                regex: /.*/
            }
        }
    }
}

Ejemplos de código JS

Juega con más funciones con la variable de acceso global PWA en su código Javascript como en los siguientes ejemplos
Este ejemplo usa la biblioteca jQuery. En la documentación podrá encontrar ejemplos en puro ES6

Botón para suscribirse a Notificaciones Push
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$('#btn1').click(() => {
    if (
        PWA.Notification.isDefault() ||
        PWA.Notification.isGranted()
    ) {
        PWA.Push.getSubscription((subscription) => {
            if (subscription) {
                $('#msg1').html('You are now subscribed to receive Push Notifications!');
            } else {
                PWA.Push.subscribe((r) => {
                    $('#msg1').html('Congratulations! You are subscribed to receive Push Notifications!');
                });
            }
        });
    } else {
        $('#msg1').html("You've turned off Push Notifications. Allow Push Notifications in your browser settings.");
    }
});
Checkbox para suscribirse / darse de baja de Notificaciones Push
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$('#switch2').click(() => {
    if (
        PWA.Notification.isDefault() ||
        PWA.Notification.isGranted()
    ) {
        PWA.Push.getSubscription((subscription) => {
            if (subscription) {
                PWA.Push.unsubscribe((r) => {
                    $('#msg2').html('You have been unsubscribed to receive Push Notifications!');
                });
            } else {
                PWA.Push.subscribe((r) => {
                    $('#msg2').html('You have been unsubscribed to receive Push Notifications!');
                });
            }
        });
    } else {
        $('#msg2').html("You've turned off Push Notifications. Allow Push Notifications in your browser settings.");
    }
});
Muestra pop-up solicitando permiso para permitir mostrar Notificaciones
1
2
3
4
5
$('#btn3').click(() => {
    PWA.Notification.requestPermission((status) => {
        $('#msg3').html(status);
    });
});
Obtener el estado de permiso de Notificaciones
1
2
3
4
$('#btn4').click(() => {
    var permission = PWA.Notification.getPermission();
    $('#msg4').html(permission);
});
Mostrar Notificación enviadas por el navegador
1
2
3
4
5
6
7
8
9
10
11
$('#btn5').click(() => {
    const options = {
        body: 'Extra content to display within the notification',
        icon: '../images/touch/chrome-touch-icon-192x192.png'
    };
    PWA.Notification.show('Notification Title', options, sent => {
        if (sent) {
            $('#msg5').html('The Notification has been sent');
        }
    });
});
Comprobar si el navegador soporta los Service Workers
1
2
3
4
5
6
7
$('#btn6').click(() => {
    if (PWA.Navigator.isSupportedServiceWorker()) {
        $('#msg6').html('This browser support Service Workers!');
    } else {
        $('#msg6').html('This browser does not support Service Workers.');
    }
});
Comprobar si el navegador soporta las Notificaciones
1
2
3
4
5
6
7
$('#btn7').click(() => {
    if (PWA.Navigator.isSupportedNotification()) {
        $('#msg7').html('This browser support Notifications!');
    } else {
        $('#msg7').html('This browser does not support Notifications.');
    }
});
Comprobar si el navegador está offline
1
2
3
4
5
6
7
$('#btn8').click(() => {
    if (PWA.Navigator.isOffline()) {
        $('#msg8').html('No Internet connection!');
    } else {
        $('#msg8').html('You have an Internet connection!');
    }
});
Borrar la caché de la aplicación del navegador
1
2
3
$('#btn9').click(() => {
    PWA.Navigator.clearCache();
});

Patio de Recreo

Juega con la biblioteca de PWA y aprende a usarla con facilidad.

jsFiddle

Repositorio

Características ⚡️ PWA a cualquier sitio web (muy rapido & Fácil)
https://github.com/jfadev/jfa-pwa-toolkit
31 tenedores.
242 estrellas.
9 problemas abiertos.
commits recientes:

  • actualización README.md, GitHub
  • actualización README.md, GitHub
  • actualización README.md, GitHub
  • actualización README.md, GitHub
  • actualización README.md, GitHub

Reddit

Dé vuelta a su sitio existente a PWA con esta biblioteca de JS from r/javascript

: ES6, javascript, Manifiesto, Offline, precache, Notificaciones Push, PWA, Service Worker
jfadev
https://jordifernandes.com
Programador y analista de sistemas desde 2006. Diplomado en Ingeniería de Software en Marsella +10 años de experiencia en Tecnologías Web. Actualmente VueJS & Symfony.

Entradas relacionadas

ECMAScript 6 (ECMAScript 2015): el nuevo estándar oficial de JavaScript aprovado

junio 19, 2015jfadev

Traducir


Mis tuits

Posts Recientes

  • JFA PWA Toolkit
  • Lista de backlinks para posicionamiento web
  • Lista completa de generadores de backlinks para posicionamiento SEO
  • Modal Dialog para Material Design Lite
  • Ejecutar comando de Symfony2 desde cronjobs en CPanel en un host compartido
  • Detectar AdBlock con jQuery o JavaScript
  • Video: Introducción a Apache Cordova en Español
  • jQuery: Cargar imagenes a medida que se necesitan (lazy load)
  • Materializecss: otro framework para Material Design
  • Directorio de más de 5.000 APIs

Enlaces Patrocinados

Categorías

  • APIs (2)
  • Frameworks (8)
  • Librerias (2)
  • Noticias (8)
  • Plugins (2)
  • Proyectos (1)
  • Codigos (1)
  • Herramientas (4)
  • Trucos (7)

Descubra

  • Los Mejores Top 10
  • Tienda Slow Fashion

Etiquetas

3D Android API Apple Apps Babylon.js Backlinks Blog Bug Chrome Extension Database E-commerce ES6 Facebook Framework Motor de juego Ghost Referrer Google Google Analytics HTML5 IndexedDB Internet of Things iOS jQuery JS Material Design Messenger Native Apps PHP Portafolio Referrer Spam Responsive Secret codes SEO SMS Spam Storage Symfony2 Editor de texto UI Web Developement WebGL Windows Phone WooCommerce Wordpress
Facebook
Gorjeo
LinkedIn
GitHub

© 2013-2020 Jordi Fernandes Alves