Progressive App Example Add to Home Screen
I am sharing my research on how to allow users to Add Website Icon on mobile device's Homescreen, just like Mobile Apps Icon(works mainly for Android devices).
Reference tutorials code
Create manifest.json at the root of the website
manifest.json
{
"name": "Example site",
"short_name": "examplesite",
"icons": [{
"src": "images/logo-96x96.png",
"sizes": "32x32",
"type": "image/png"
},
{
"src": "images/logo-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "images/logo-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "/?utm_source=web_app_manifest",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#000000"
}
Add following code in head part of the HTML of Index page
<meta name="theme-color" content="#000000"/>
<link rel="manifest" href="/manifest.json" />
Add following JS code in the footer of Index page
if (window.matchMedia('(display-mode: standalone)').matches) {
console.log('display-mode is standalone');
}
if (window.navigator.standalone === true) {
console.log('display-mode is standalone');
}
window.addEventListener('appinstalled', (evt) => {
//app.logEvent('a2hs', 'installed');
});
let deferredPrompta;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompta = e;
// very important to prompt flyout
deferredPrompta.prompt();
});
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/service-worker.js').
then(function (registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
Finally create service-worker.js at the root of the website
server-worker.js
self.addEventListener('install', function (event) {});
self.addEventListener('activate', function (event) {});
self.addEventListener('fetch', function (event) {});
No comments:
Post a Comment