Reputation: 143
i want to add custom install
button for my progressive web app within the site. i red many articles and tried the answer provided by them. they use beforeinstallprompt
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
deferredPrompt = e;
});
but the problem i am facing is i want the button to directly installed the pwa instead of triggering the installation prompt. is it possible, if so how can i achieve that. thanks you in advance.
Upvotes: 14
Views: 24373
Reputation: 910
No, you cannot do it just like that, it takes a bit more. Please see my recent answer.
You will find short but comprehensive instructions with code samples. The installation prompt is triggered by a button on a main application, and this button is only visible when the application is not installed as PWA.
Upvotes: 0
Reputation: 1
Try below code,
Step 1 - Create button or any controller
<button id="installApp">Install</button>
Step 2 - Add below js code in your scripts noy in serviceworker
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
deferredPrompt = e;
});
const installApp = document.getElementById('installApp');
installApp.addEventListener('click', async () => {
if (deferredPrompt !== null) {
deferredPrompt.prompt();
const { outcome } = await deferredPrompt.userChoice;
if (outcome === 'accepted') {
deferredPrompt = null;
}
}
});
Upvotes: 17
Reputation: 84
I know it might be late, but I would like to share my answer, in case someone needs it.
if ('serviceWorker' in navigator && 'PushManager' in window) {
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault();
const deferredPrompt = e;
const installButton = document.createElement('button');
installButton.textContent = 'Install App';
installButton.style.position = 'fixed';
installButton.style.top = '10px';
installButton.style.left = '50%';
installButton.style.transform = 'translateX(-50%)';
installButton.style.zIndex = '9999';
installButton.style.padding = '10px 20px';
installButton.classList.add('btn-grad');
installButton.style.color = 'white';
installButton.style.border = 'none';
installButton.style.borderRadius = '5px';
installButton.style.cursor = 'pointer';
installButton.addEventListener('click', () => {
deferredPrompt.prompt();
deferredPrompt.userChoice.then(choiceResult => {
if (choiceResult.outcome === 'accepted') {
console.log('App installed');
} else {
console.log('App installation declined');
}
installButton.style.display = 'none';
});
});
document.body.appendChild(installButton);
});
}
This exactly does what you want. And is compatible with most modern browsers.
Upvotes: 6
Reputation: 607
The answer is, you can't. According to the manifest spec:
By design, this specification does not provide developers with an explicit API to "install" a web application.
Upvotes: 12