mdinfotech.net  



PWA
Progressive Web Apps (PWAs) are web applications that load like regular web pages or websites but can offer the user functionality such as working offline, push notifications, and device hardware access traditionally available only to native mobile applications.
  • Watch: What is a PWA?
  • For more info: Google's Intro To Progressive Web Apps
  • manifest
    Progressive Web Apps require a manifest which is a JSON file that contains information about how your app should appear when installed on a mobile device.
    icons
    App icons are crucial for branding. It is the first thing a user interacts with, even before launching your app. On mobile devices, icons are placed on the home screen. A quality graphic for the icon adds to users’ intuition to tap open the application. In PWA' (Progressive Web Apps)'s, the icons are configurable in the manifest file. Read more about app icons: How to Define App Icons.

    Add the manifest and icons to your TV Maze Assignment:

    1. Rename the main html file index.html if it isn't already.
    2. Get an icon: You'll need icons for different screen sizes. Two key sizes are 192x192 and 512x512 pixels, but others can be used as well. Create your own 512x512 icon or go to FlatIcon.
    3. Get a manifest and icons of different sizes: Use a website like PWA Manifest Generator to generate a manifest and a maskable icon. Another option is App Icon Generator to generate icons of different sizes but then you have to write your own manifest.
    4. Create an icons folder: Place these icons in your app's icons directory and the manifest in the root directory (same directory as index.html).
    5. Update the locations of the icons in the manifest. For a full explanation of the manifest file: https://pwa-workshop.js.org/1-manifest/.
    6. Add the manifest to your base HTML template by putting the tag link rel="manifest" href="manifest.json" into the head.
    7. Test if your manifest is working. You can check that the manifest is retrieved correctly by looking in the Applications tab of Chrome Developer Tools. The list of manifest properties and the icons should be displayed.

    PWAs require a secure context (HTTPS) to be installable. This means you must host your PWA on a service that provides HTTPs (vs HTTP). Github offers this service for free.

    Here's how you can host a website on GitHub using only GitHub’s web interface:

    Step 1: Create a GitHub Repository

    1. Log in to your GitHub account (or sign up if you don’t have one).
    2. Create a new repository:
      • Click the "+" icon in the top-right corner of the GitHub dashboard and select New Repository.
      • Give the repository the name username.github.io but replace username with your github username.
      • Choose Public (so GitHub Pages can serve it).
      • Do not initialize the repository with a README (you’ll add files in the next step).
      • Click Create repository.

    Step 2: Upload Your Website Files to GitHub

    1. Navigate to the repository you just created.
    2. Click on the Add file button, then select Upload files.
    3. Drag and drop your website files (HTML, CSS, JavaScript, etc.) into the upload box.
      • At minimum, you’ll need an index.html file, which will serve as the main page of your website.
      • Note: You will need to update your manifest `Start-URL` to be the name of your Github project followed by a forward slash. For example, if your Github project is called `pwa-test` your Start URL is `pwa-test/`.
    4. After you’ve uploaded your files, scroll down and click the Commit changes button. This will save the files to your repository.

    Step 3: Enable GitHub Pages

    1. In the repository, go to the Settings tab at the top of the page.
    2. On the left-hand sidebar, click on the Pages section (it may be located near the bottom).
    3. Under the Source section, select "Deploy from a Branch".
    4. Under Branch, choose the branch that contains your website files (probablymaster). Leave the folder as / (root) if your website files are in the root of the repository.
    5. Click Save.

    Step 4: Visit Your Published Website

    1. Once GitHub finishes processing your site (this usually takes a minute or two), you’ll see a message at the top of the Pages section that shows the URL where your site is hosted.
      • The URL will typically look like: https://username.github.io/foldercontainingyoursite.
    2. Click the link to view your live website!

    Step 5: Update Your Website

    • Anytime you want to make changes to your website, you can return to the repository and upload new files through the Add file -> Upload files option.
    • GitHub Pages will automatically update your site with the new content once you commit your changes. These changes can take up to 10 minutes to show up.

    That's it! Your website is now hosted on GitHub Pages, and you can manage everything directly through GitHub's web interface.

    Watch What is a Service Worker?. For a more detailed explanation watch Introduction to Service Workers.
    1. Use this service worker code. Save it as sw.js in the root of the scope you used in the manifest (likely the same folder as your index.html) It precaches files and fetches to the API that have been made.
    2. Modify the cache to include all the files you want cached for offline use.
    3. Add a code block to your base js file to load the service worker. It should be something like
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('/sw.js').then(function(registration) {
            console.log('Service Worker registered with scope:', registration.scope);
          }, function(error) {
            console.log('Service Worker registration failed:', error);
          });
        });
      }                    
                          
    1. To prompt the user to install your PWA, listen for the beforeinstallprompt event.
    2. This event is triggered when the app meets installability criteria (like having a valid manifest and service worker).
    3. Copy the code below into your script.js file to handle the install prompt:
      // handle install prompt
      let deferredPrompt;
      
      window.addEventListener('beforeinstallprompt', (e) => {
        e.preventDefault();
        deferredPrompt = e;
      
        const installButton = document.getElementById('installButton');
        installButton.style.display = 'block';
      
        installButton.addEventListener('click', () => {
          installButton.style.display = 'none';
          deferredPrompt.prompt();
          deferredPrompt.userChoice.then((choiceResult) => {
            if (choiceResult.outcome === 'accepted') {
              console.log('User accepted the install prompt');
            } else {
              console.log('User dismissed the install prompt');
            }
            deferredPrompt = null;
          });
        });
      });                    
                          
    4. Add an install button in your HTML where users can click to install the PWA. This will be shown when beforeinstallprompt is run by the service worker.
      install button code
    1. Use Chrome DevTools to verify that your PWA is installable.
      • Open DevTools (F12 or right-click -> Inspect), then go to the Application tab.
      • Check under "Manifest" to see if the manifest is correctly detected.
      • Check under "Service Workers" to ensure your service worker is active.
    2. You can also test installability by visiting your app on mobile, where you should see an "Add to Home Screen" option.

    All the instructions above are summarized here: How to Make A PWA

    The Service Worker you were given in earlier should cache all your code files, and images that are part of your interface. This allows your app to be loaded offline. In addition, it should also cache any fetches made by the app while it is online. What this means is if the app is being used offline, and a fetch is made that was cached, then it will load the data from that fetch and appear like it is working.

  • Follow these instructions Service Workers - Caching Fetch Events
  • Research

    Read the following article: 3 Rules of App Design.

    The Project

    Write a Progressive Web App that uses the Open Trivia Database API. Be creative in your app design and utilize the API to make an app that users will install and use over and over again. Code that is taken from tutorials or other sources other than yourself is clearly commented with a link to the source. If credit is claimed for code that is not yours, the project will not be accepted.

    Here is a very "in development" game created using the Bored API: Ms. Wear's Bored API Game Example. This is not good enough to justify a final project, as it is too simple. However, it does demonstrate how to use the API data from the Bored API creatively. It is a much more interesting use of the data than just displaying the fetch response in the webpage.

    Milestones

    1. Tuesday Jan 9: Share your app idea (how will you use the API creatively)
    2. Thursday Jan 11: Basic responsive layout complete (not styled yet) and at least 1 piece of data from an API fetch is shown
    3. Tuesday Jan 16: Finish API related functionality
    4. Friday Jan 19: Finish layout and styling
    5. Tuesday Jan 23: In class marking of PWA and code
    6. Wednesday Jan 24 (3 hour class): In class demonstration of Final App

    Marking Rubric

    Functionality and Complexity(/10)
    1. The work you put in is justifiably worth 20% of your mark. You have written a significant amount of JavaScript, and responsive CSS/HTML on your own. Only code and functionality created by you will be assessed.
    2. Creative use of API data. Has actual original JS code that allows user interactions and creatively utilizes data from the API
    3. Is entertaining or useful enough that users will install it and use it repeatedly
    4. Works on a desktop/laptop and a mobile android device
    5. Robust (the user cannot cause it to crash) and Reliable (never crashes on its own and always works as expected)
    	10	                8	                    6	                4	            < 4	 	
    	All criteria met	Most criteria met	Some criteria met	Multiple Issues	    Incomplete		
    	All criteria met	1 -2 issues	        3-4 small issues and/or 1 big issue        4+ problems	    A static HTML/CSS website was submitted.
    
    Meets Progressive Web App Criteria (/5)
    1. Manifest is recognized and contains basic required info.
    2. Icon used with multiple required sizes for the icon to show up on splash screen and desktop icons.
    3. Manifest refers to multiple sizes of icons.
    4. Service worker that preloads cached files works and app can be used offline. Caches previous fetches so these results can be loaded if the user goes offline.
    5. Chrome's "Install App Name..." creates a working shortcut that opens to the sites homepage, with an appropriate title, in standalone mode (that is, the browser window is not visible).
    6. Lighthouse Audit: all 4 non-PWA criteria in the Green Zone, and of the PWA criteria: it is installable (green circle) and at least 5 of the 6 PWA Optimized criteria have green circles.
    	5	                4	                    3	                2	            1		
    	All criteria met	Most criteria met	Some criteria met	Multiple Issues	    Incomplete		
    	All criteria met	1 -2 issues	        3-4 small issues        4+ problems	    Minimal attempt to create PWA.
    
    Usability and Presentation (/5)
    1. easy to use
    2. applies principles of design
    3. attractive design using colors, fonts, css positioning, css effects
    4. responsive design
    5. Appropriate icon used without breaking copyright.
    6. Offline: Loads the main html, css, and js and indicates that you need to be online in order for the app to work.
    	5	                4	                    3	                2	            1		
    	All criteria met	Most criteria met	Some criteria met	Multiple Issues	    Incomplete		
    	All criteria met	1 -2 issues	        3-4 small issues        4+ problems	    Minimal attempt to create attractive, responsive, usable design.
    
    Code (/5)
    1. HTML Validates
    2. CSS Validates
    3. There is only one CSS file
    4. There is only one JS file
    5. No JS Error in console
    6. Practices separation of languages
    7. Code that is taken from tutorials or other sources other than yourself is clearly commented with a link to the source. If credit is claimed for code that is not yours, the project will not be accepted.
    	5	                4	                3	                2	            1		
    	All criteria met	Most criteria met	Some criteria met	Multiple issues	    Incomplete		
    	All criteria met	1 -2 issues	        3-4  issues	        4+ problems         Not coded to standards taught in class.					
    	
    			

    Here are some free APIs that provide content in JSON format, which could be useful for your web app:

    1. OpenWeatherMap API

    • Content: Current weather data, forecasts, and historical data.
    • Use: Great for weather-related features.
    • Endpoint: https://api.openweathermap.org/data/2.5/weather
    • OpenWeatherMap

    2. NewsAPI

    • Content: News headlines, articles from various sources.
    • Use: Ideal for integrating a news feed or headlines.
    • Endpoint: https://newsapi.org/v2/top-headlines
    • NewsAPI

    3. Unsplash API

    • Content: Free images from photographers.
    • Use: For adding images to your app, such as backgrounds or image galleries.
    • Endpoint: https://api.unsplash.com/photos
    • Unsplash API

    4. The Cat API / The Dog API

    • Content: Random images of cats and dogs.
    • Use: Fun images of pets to liven up your web app.
    • Endpoint: https://api.thecatapi.com/v1/images/search
    • The Cat API / The Dog API

    5. CoinGecko API

    • Content: Cryptocurrency prices, market data, and trends.
    • Use: For financial apps or crypto-related features.
    • Endpoint: https://api.coingecko.com/api/v3/coins/markets
    • CoinGecko

    6. Open Library API

    • Content: Data on books, including authors, subjects, and covers.
    • Use: Book recommendations, search functionalities for books.
    • Endpoint: https://openlibrary.org/api/books
    • Open Library API

    7. JokeAPI

    • Content: Random jokes, including specific categories like programming jokes.
    • Use: Add humor or generate fun content for your users.
    • Endpoint: https://v2.jokeapi.dev/joke/Any
    • JokeAPI

    8. Open Trivia Database

    • Content: Trivia questions on a wide range of topics.
    • Use: To add trivia games or quizzes to your app.
    • Endpoint: https://opentdb.com/api.php
    • Open Trivia DB

    9. REST Countries API

    • Content: Data about countries, such as population, languages, and flags.
    • Use: Apps with geographical or educational features.
    • Endpoint: https://restcountries.com/v3.1/all
    • REST Countries

    10. Advice Slip API

    • Content: Random pieces of advice.
    • Use: Provide users with motivational or fun advice.
    • Endpoint: https://api.adviceslip.com/advice
    • Advice Slip API

    These APIs are easy to integrate and allow you to retrieve content in JSON format, making them perfect for web applications. Let me know if you need help with implementation or additional suggestions!

    If you choose an API that requires a hidden API key, or is giving you CORS errors on glitch, use this example.
    Ms. Wear's Example of Hidden API Keys and Preventing CORS errors on Glitch