In the last post I had shared with you how to make the browser show a "Add to Home Screen" dialog box in Mobile devices. It is possible in both Android, iOS and even on Latest desktop browsers too. This feature is available in modern web browser and it helps us to install the PWA in user's device.
In this post we will learn how to show Add to Home Screen prompt when user clicks a button. The dialog box like the image below will popup on user's screen once they click the button designed to do that task. Below is the Add to home screen popup dialog box.

To popup add to home screen dialog box all we need to do is -
- Trash the beforeinstallprompt
- Call deferredPrompt.prompt() when a custom button is cliked
Who wants to waste time in reading. So here's the code for you.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta name='viewport' content='width=device-width'> | |
<link rel="manifest" href="./manifest.json"> | |
<title>Page title</title> | |
</head> | |
<body onload='a2hsinit()'> | |
<button onclick='install()'>Add to home screen</button> | |
<script type="text/javascript"> | |
//register service worker | |
if ('serviceWorker' in navigator) { | |
navigator.serviceWorker.register('service-worker.js') | |
.then(function(reg){ | |
console.log("Service service-worker registered"); | |
}).catch(function(err) { | |
console.warn("service-worker didnt work, "+ err); | |
}); | |
} | |
//trash the beforeinstallprompt event | |
function a2hsinit(){ | |
window.addEventListener('beforeinstallprompt', function(e){ | |
e.preventDefault(); | |
console.log('beforeinstallprompt fired'); | |
if(e.prompt){ | |
window.deferredPrompt = e; | |
return false; | |
} | |
}); | |
} | |
//trigger deferredPrompt to allow the user install PWA | |
function install(){ | |
deferredPrompt.prompt(); | |
} | |
</script> | |
</body> | |
</html> |
NOTE : manifest.json and service-worker.js file needs to be available in the same directory. Refer to last post to learn how to do that.
Check and download source code from this link https://xbytelab.com/project/add_to_home_screen_onclick
Comments
Post a Comment