Skip to content

Single JavaScript file to convert any HTML page into a fully functional Progressive Web App. CDN-ready, zero setup, works everywhere. Made with privacy in mind.

License

Notifications You must be signed in to change notification settings

xsukax/xsukax-PWA-Transformer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ xsukax PWA Transformer

Transform any website into a Progressive Web App with a single line of code.

License: GPL v3 Version CDN

πŸ“‹ Project Overview

xsukax PWA Transformer is a lightweight, zero-dependency JavaScript library that instantly converts any website into a fully-functional Progressive Web App. By adding a single script tag to your HTML, you gain offline capabilities, installability across all platforms, and enhanced user engagement without complex configuration or build processes.

The library automatically generates web app manifests, registers service workers with intelligent caching strategies, handles installation prompts, and provides comprehensive PWA lifecycle management. It supports both CDN-based deployment for instant integration and local hosting for customized implementations.

Primary Use Cases:

  • Converting existing websites to installable PWAs
  • Adding offline functionality to web applications
  • Enabling "Add to Home Screen" on mobile devices
  • Creating standalone desktop applications from web content
  • Rapid PWA prototyping and development

πŸ”’ Security and Privacy Benefits

xsukax PWA Transformer is designed with privacy-first principles and robust security measures:

Privacy Protection

  • Zero Tracking: No analytics, telemetry, or user data collection of any kind
  • No External Dependencies: All functionality is self-contained with no third-party library calls
  • Local Processing: Manifest generation and configuration occur entirely client-side
  • No Server Communication: Beyond the initial CDN script load, no data is transmitted to external servers
  • User Control: Complete control over cached resources and service worker behavior

Security Features

  • Content Security Policy Compatible: Works seamlessly with strict CSP implementations
  • HTTPS Enforcement: Service workers require HTTPS, ensuring encrypted communication
  • Scope Isolation: Service worker scope can be restricted to specific paths
  • Origin Validation: Only serves cached content from the same origin
  • Transparent Caching: Clear cache management APIs for user data control
  • Open Source Transparency: Fully auditable GPL-3.0 licensed codebase

Data Integrity

  • Version Control: Automatic cache versioning prevents stale content issues
  • Cache Invalidation: Configurable maximum age for cached resources
  • Network-First Fallback: Ensures fresh content when network is available
  • Background Sync Support: Built-in sync event handling for future extensibility

✨ Features and Advantages

Core Capabilities

  • One-Line Integration: Single <script> tag deployment via CDN
  • Automatic Manifest Generation: Creates compliant web app manifests dynamically
  • Service Worker Management: Handles registration, updates, and lifecycle events
  • Multiple Cache Strategies: Network-first, cache-first, and stale-while-revalidate options
  • Cross-Platform Installation: Works on Windows, macOS, Linux, Android, and iOS
  • Offline Functionality: Continues working without internet connectivity
  • Install Prompt Control: Deferred installation with custom UX integration
  • Update Notifications: Automatic detection and handling of new versions

Developer Experience

  • Zero Configuration: Works out-of-the-box with sensible defaults
  • Flexible API: Programmatic control over all PWA aspects
  • Debug Mode: Comprehensive logging for development troubleshooting
  • Multiple CDN Options: jsDelivr, GitHub Raw, and Statically support
  • Customizable Icons: Default SVG icons or custom image support
  • Event System: Custom events for install, update, and network status changes
  • Callback Hooks: Integration points for application-specific logic

Production Ready

  • Lightweight: Minimal footprint with no external dependencies
  • Browser Compatible: Works on all modern browsers supporting service workers
  • Mobile Optimized: Special handling for iOS and Android platforms
  • Error Handling: Graceful degradation when features are unavailable
  • Performance Focused: Efficient caching and minimal runtime overhead
  • GPL-3.0 Licensed: Free for commercial and personal use

πŸ“¦ Installation

CDN Usage (Recommended)

The simplest way to use xsukax PWA Transformer is via CDN. Add this single line to your HTML:

<script src="https://cdn.jsdelivr.net/gh/xsukax/xsukax-PWA-Transformer@main/pwa.js" 
        data-auto-init 
        data-app-name="My Application" 
        data-theme-color="#4a90e2"></script>

That's it! Your website is now a PWA with offline support and installation capability.

Available CDN Providers

jsDelivr (Recommended - Fast & Reliable):

https://cdn.jsdelivr.net/gh/xsukax/xsukax-PWA-Transformer@main/pwa.js

GitHub Raw:

https://raw.githubusercontent.com/xsukax/xsukax-PWA-Transformer/main/pwa.js

Statically:

https://cdn.statically.io/gh/xsukax/xsukax-PWA-Transformer/main/pwa.js

Local Installation

For custom deployments or offline development:

  1. Download the library files:
git clone https://github.com/xsukax/xsukax-PWA-Transformer.git
  1. Copy pwa.js and optionally sw.js to your web root

  2. Reference the local file:

<script src="/path/to/pwa.js" data-auto-init data-app-name="My App"></script>

🎯 Usage Guide

Quick Start with Auto-Initialization

The easiest approach uses data attributes for configuration:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My PWA</title>
</head>
<body>
  <h1>Welcome to My PWA</h1>
  
  <!-- One-line PWA transformation -->
  <script src="https://cdn.jsdelivr.net/gh/xsukax/xsukax-PWA-Transformer@main/pwa.js" 
          data-auto-init 
          data-app-name="My Progressive Web App" 
          data-app-short-name="My PWA"
          data-theme-color="#667eea" 
          data-background-color="#ffffff"></script>
</body>
</html>

Manual Initialization for Advanced Control

For programmatic configuration and custom behavior:

<script src="https://cdn.jsdelivr.net/gh/xsukax/xsukax-PWA-Transformer@main/pwa.js"></script>
<script>
  PWA.init({
    appName: 'My Application',
    appShortName: 'MyApp',
    appDescription: 'A powerful progressive web application',
    themeColor: '#4a90e2',
    backgroundColor: '#ffffff',
    cacheStrategy: 'networkFirst', // or 'cacheFirst', 'staleWhileRevalidate'
    cacheUrls: ['/', '/index.html', '/styles.css', '/app.js'],
    cacheMaxAge: 86400, // 24 hours in seconds
    debug: true, // Enable console logging
    onInstalled: () => {
      console.log('App successfully installed!');
    },
    onUpdateAvailable: (newWorker) => {
      if (confirm('New version available. Update now?')) {
        newWorker.postMessage({ type: 'SKIP_WAITING' });
        window.location.reload();
      }
    },
    onOffline: () => {
      console.log('Working in offline mode');
    },
    onOnline: () => {
      console.log('Back online!');
    }
  });
</script>

Adding an Install Button

Integrate custom installation UI into your application:

<button id="installBtn" style="display: none;">Install App</button>

<script>
  // Show button when installation is available
  window.addEventListener('pwa-install-available', () => {
    document.getElementById('installBtn').style.display = 'block';
  });

  // Handle installation
  async function installApp() {
    const installed = await PWA.install();
    if (installed) {
      alert('App installed successfully!');
      document.getElementById('installBtn').style.display = 'none';
    } else {
      alert('Installation cancelled or unavailable');
    }
  }
  
  document.getElementById('installBtn').onclick = installApp;
</script>

Service Worker Configuration

The library automatically attempts to load sw.js with intelligent fallback:

  1. Local file: Checks for ./sw.js in your web root
  2. CDN fallback: Uses https://cdn.jsdelivr.net/gh/xsukax/xsukax-PWA-Transformer@main/sw.js
  3. Manual download: Call PWA.downloadServiceWorker() to download the file
// Download service worker for local hosting
PWA.downloadServiceWorker();

// Check service worker status
const info = PWA.getInfo();
if (info.registration) {
  console.log('Service worker active');
} else {
  console.log('Service worker not registered');
}

Cache Management

Control cached resources programmatically:

// Clear all cached data
await PWA.clearCache();

// Unregister service worker completely
await PWA.unregister();

// Get comprehensive PWA information
const info = PWA.getInfo();
console.log('Initialized:', info.initialized);
console.log('Can Install:', info.canInstall);
console.log('Is Standalone:', info.isStandalone);
console.log('Is Online:', info.isOnline);
console.log('Platform:', info.isMobile ? 'Mobile' : 'Desktop');

Event Handling

Listen to PWA lifecycle events:

// Installation available
window.addEventListener('pwa-install-available', (event) => {
  console.log('PWA can be installed');
  // Show custom install UI
});

// Installation completed
window.addEventListener('pwa-installed', (event) => {
  console.log('PWA has been installed');
  // Hide install UI, show confirmation
});

// Network status changes
window.addEventListener('online', () => {
  console.log('Network connection restored');
});

window.addEventListener('offline', () => {
  console.log('Network connection lost');
});

πŸ—οΈ Architecture

System Overview

graph TB
    A[Web Page] -->|Includes| B[pwa.js]
    B -->|Generates| C[Web App Manifest]
    B -->|Registers| D[Service Worker]
    B -->|Injects| E[Meta Tags]
    
    C -->|Enables| F[Installation]
    D -->|Provides| G[Offline Support]
    D -->|Manages| H[Cache Storage]
    
    F -->|Triggers| I[Install Prompt]
    G -->|Uses| J[Cache Strategies]
    H -->|Stores| K[App Resources]
    
    style B fill:#4a90e2,color:#fff
    style D fill:#667eea,color:#fff
    style F fill:#2e7d32,color:#fff
Loading

Initialization Flow

sequenceDiagram
    participant User
    participant Browser
    participant PWA as pwa.js
    participant SW as Service Worker
    participant Cache
    
    User->>Browser: Load webpage
    Browser->>PWA: Execute script
    PWA->>PWA: Read configuration
    PWA->>Browser: Inject meta tags
    PWA->>Browser: Generate manifest
    PWA->>Browser: Register SW
    Browser->>SW: Install & activate
    SW->>Cache: Precache resources
    SW-->>PWA: Registration complete
    PWA->>Browser: Setup install prompt
    PWA->>User: PWA ready
    
    Note over User,Cache: App is now installable and offline-capable
Loading

Cache Strategy Flow

graph LR
    A[Request] --> B{Strategy?}
    
    B -->|Network First| C[Try Network]
    C -->|Success| D[Update Cache]
    C -->|Fail| E[Return Cache]
    
    B -->|Cache First| F[Check Cache]
    F -->|Hit| G[Return Cache]
    F -->|Miss| H[Fetch Network]
    H --> I[Update Cache]
    
    B -->|Stale While Revalidate| J[Return Cache]
    J --> K[Update in Background]
    
    style B fill:#667eea,color:#fff
    style D fill:#2e7d32,color:#fff
    style I fill:#2e7d32,color:#fff
Loading

πŸ› οΈ API Reference

Core Methods

PWA.init(config)

Initialize the PWA with custom configuration.

Parameters:

  • config (Object): Configuration options

Returns: Promise

Example:

await PWA.init({
  appName: 'My App',
  themeColor: '#4a90e2',
  cacheStrategy: 'networkFirst'
});

PWA.install()

Trigger the installation prompt.

Returns: Promise - true if installed, false if cancelled

Example:

const installed = await PWA.install();
if (installed) {
  console.log('App installed!');
}

PWA.canInstall()

Check if the app can be installed.

Returns: boolean

Example:

if (PWA.canInstall()) {
  document.getElementById('installBtn').style.display = 'block';
}

PWA.isStandalone()

Check if the app is running in standalone mode (installed).

Returns: boolean

Example:

if (PWA.isStandalone()) {
  console.log('Running as installed app');
}

PWA.isOnline()

Check current network connectivity status.

Returns: boolean

Example:

if (!PWA.isOnline()) {
  showOfflineMessage();
}

PWA.downloadServiceWorker()

Download the service worker file to local storage.

Returns: void

Example:

PWA.downloadServiceWorker();
// File will be downloaded as 'sw.js'

PWA.clearCache()

Clear all cached resources.

Returns: Promise

Example:

await PWA.clearCache();
console.log('Cache cleared');

PWA.unregister()

Unregister the service worker.

Returns: Promise

Example:

await PWA.unregister();
console.log('Service worker unregistered');

PWA.getInfo()

Get comprehensive PWA status and configuration.

Returns: Object with properties:

  • initialized (boolean)
  • config (Object)
  • registration (ServiceWorkerRegistration|null)
  • canInstall (boolean)
  • isStandalone (boolean)
  • isOnline (boolean)
  • isMobile (boolean)
  • isIOS (boolean)
  • supportsServiceWorker (boolean)

Example:

const info = PWA.getInfo();
console.log('PWA Status:', info);

Configuration Options

{
  // Application Identity
  appName: 'Progressive Web App',           // Full application name
  appShortName: 'PWA',                       // Short name (12 chars max)
  appDescription: 'Powered by xsukax',       // App description
  appVersion: '1.0.0',                       // Version number
  
  // Appearance
  themeColor: '#4a90e2',                     // Theme/toolbar color
  backgroundColor: '#ffffff',                // Splash screen background
  displayMode: 'standalone',                 // Display mode: standalone, fullscreen, minimal-ui, browser
  orientation: 'any',                        // Orientation: any, portrait, landscape
  
  // Routing
  scope: './',                               // Service worker scope
  startUrl: './',                            // Launch URL
  
  // Caching
  cacheName: 'pwa-cache-v1',                 // Cache identifier
  cacheStrategy: 'networkFirst',             // Cache strategy: networkFirst, cacheFirst, staleWhileRevalidate
  cacheUrls: ['/'],                          // URLs to precache
  cacheMaxAge: 86400,                        // Max cache age in seconds
  
  // Service Worker
  swPath: 'sw.js',                           // Service worker file path
  swCdnUrl: 'https://cdn.jsdelivr.net/...',  // CDN fallback URL
  swScope: './',                             // Service worker scope
  skipWaiting: true,                         // Auto-activate new SW
  clientsClaim: true,                        // Control clients immediately
  
  // Installation
  enableInstallPrompt: true,                 // Enable install functionality
  deferInstallPrompt: true,                  // Defer prompt for custom UI
  
  // Icons (array of icon objects)
  icons: [
    {
      src: 'icon-192.png',
      sizes: '192x192',
      type: 'image/png',
      purpose: 'any'
    }
  ],
  
  // Callbacks
  onInstalled: () => {},                     // Called when app is installed
  onUpdateAvailable: (newWorker) => {},      // Called when update is available
  onOffline: () => {},                       // Called when going offline
  onOnline: () => {},                        // Called when going online
  
  // Development
  debug: false                               // Enable debug logging
}

Events

The library dispatches custom events you can listen to:

// Installation available
window.addEventListener('pwa-install-available', (event) => {
  // event.detail.canInstall = true
});

// Installation completed
window.addEventListener('pwa-installed', (event) => {
  // App has been installed
});

πŸ“± Platform-Specific Notes

iOS Support

  • iOS displays installation instructions automatically
  • No programmatic install prompt on iOS (platform limitation)
  • Users must manually add via Share β†’ Add to Home Screen

Android Support

  • Full install prompt support
  • Native "Add to Home Screen" experience
  • Chrome and Edge provide install banners

Desktop Support

  • Chrome, Edge, and Opera support desktop installation
  • Appears as standalone application in OS
  • Full window chrome control

πŸ”§ Troubleshooting

Service Worker Not Registering

// Enable debug mode to see detailed logs
PWA.init({ debug: true });

// Check browser support
if (!PWA.getInfo().supportsServiceWorker) {
  console.log('Service workers not supported');
}

Installation Not Available

// Check install capability
if (!PWA.canInstall()) {
  console.log('Cannot install:', 
    PWA.isStandalone() ? 'Already installed' : 'Install prompt not available'
  );
}

Cache Issues

// Clear cache and reload
await PWA.clearCache();
window.location.reload();

// Unregister and start fresh
await PWA.unregister();
await PWA.init(config);

πŸ“„ License

This project is licensed under the GNU General Public License v3.0.

πŸ™ Credits

Author: xsukax
Website: xsukax.com
GitHub: github.com/xsukax

Copyright Β© 2025 xsukax


Made with ❀️ for the open-source community