Based on Abdelrahman Omran PWA presentation, and Google PWA Codelab
- Activate Application Scripts
- Save Cities to localStorage
- Use Saved Cities at App Startup
- Add Event Handler for Add City Button
Step 2. Use service workers to pre-cache the App Shell
Step 3. Use service workers to cache the forecast data
Step 4. Support native integration & Deploy online
Open index.html and uncomment the following line:
<!--<script src="scripts/app.js" async></script>-->Open scripts/app.js and search for the following line:
// TODO add saveSelectedCities function hereAdd the following code below the previous comment:
// Save list of cities to localStorage.
app.saveSelectedCities = function() {
var selectedCities = JSON.stringify(app.selectedCities);
localStorage.selectedCities = selectedCities;
};Note: you should be using
IndexedDBor another fast storage mechanism to store user preferences, but we've usedlocalStoragefor codelab simplicity, which is not ideal for production apps because it is a blocking, synchronous storage mechanism that is potentially very slow on some devices.
Open scripts/app.js and search for the following line:
// TODO add startup code hereAdd the following code below the previous comment:
// Get saved cities from cache
app.selectedCities = localStorage.selectedCities;
if (app.selectedCities) {
app.selectedCities = JSON.parse(app.selectedCities);
app.selectedCities.forEach(function(city) {
app.getForecast(city.key, city.label);
});
} else {
// First usage for the user, so use fake data & save fake city for later usage.
// A real app in this scenario could guess the user's location via IP lookup.
app.updateForecastCard(initialWeatherForecast);
// Select fake city
app.selectedCities = [
{key: initialWeatherForecast.key, label: initialWeatherForecast.label}
];
// Save selected cities
app.saveSelectedCities();
}Open scripts/app.js and search for the following line:
// TODO init the app.selectedCities array hereAdd the following code below the previous comment:
if (!app.selectedCities) {
app.selectedCities = [];
}In the same file scripts/app.js search for the following line:
// TODO push the selected city to the array and save hereAdd the following code below the previous comment:
// Push selected cities to the array
app.selectedCities.push({key: key, label: label});
// Save selected cities
app.saveSelectedCities();Note: you can now check your PWA application in your browser, you should be able to add cities and see weather forcast for saved cities even after page reload.