Last active
September 9, 2016 20:32
-
-
Save PaulKinlan/0ef4f7bb5ddbd90127fe to your computer and use it in GitHub Desktop.
window.install
This file contains hidden or 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
(function() { | |
var deferredInstall; | |
var promptTriggered = false; | |
// The resolve function that will be called when we know we can prompt. | |
var canPromptPromiseResolved; | |
var canPromptPromise = new Promise(function(resolve, reject) { | |
// The resolve will be called later when we know the prompt has been shown. | |
// We might want to reject after a timeout of a couple of seconds. | |
canPromptPromiseResolved = resolve; | |
}); | |
window.addEventListener('beforeinstallprompt',function(e) { | |
promptTriggered = true; | |
// Stop it doing what it needs to do; | |
e.preventDefault(); | |
deferredInstall = e; | |
// Resolve the promise, to say that we know we can prompt. | |
canPromptPromiseResolved(); | |
return false; | |
}); | |
var install = {}; | |
Object.defineProperty(install, 'isAvailable', { get: function() { return promptTriggered; } }); | |
install.canPrompt = function() { | |
return canPromptPromise; | |
}; | |
install.prompt = function () { | |
return new Promise(function(resolve, reject){ | |
if(promptTriggered === false) { | |
// There can be a whole host or reasons, we should determine them | |
reject('User Agent decided not to prompt'); | |
}; | |
deferredInstall.prompt().then(function() { | |
return deferredInstall.userChoice | |
}).then(function(choice) { | |
resolve(choice.outcome); | |
}).catch(function(reason) { | |
reject(reason); | |
}); | |
}); | |
}; | |
window.install = install; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment