I have a deployed app with a secure connection (https).
I managed to add it to my android home screen using this feature in Google Chrome:
The problem is that users aren't likely to do this if I don't add a button that does that in the app.
After a bit of research, I tried to adapt the code here to my React app.
So I transformed this:
let deferredPrompt;
const addBtn = document.querySelector(".add-button");
addBtn.style.display = "none";
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.
deferredPrompt = e;
// Update UI to notify the user they can add to home screen
addBtn.style.display = "block";
addBtn.addEventListener("click", (e) => {
// hide our user interface that shows our A2HS button
addBtn.style.display = "none";
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === "accepted") {
console.log("User accepted the A2HS prompt");
} else {
console.log("User dismissed the A2HS prompt");
}
deferredPrompt = null;
});
});
});
To this:
export class AddToHomeScreenButton extends Component {
constructor() {
super();
this.state = {
deferredPrompt: null,
};
this.onClick = this.onClick.bind(this);
}
componentDidMount() {
let deferredPrompt;
window.addEventListener("beforeinstallprompt", (e) => {
console.log(
" ~ file: AddToHomeScreenButton.js:46 ~ AddToHomeScreenButton ~ window.addEventListener ~ beforeinstallprompt"
);
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
console.log(
" ~ file: AddToHomeScreenButton.js:22 ~ AddToHomeScreenButton ~ window.addEventListener ~ deferredPrompt",
deferredPrompt
);
this.setState({ deferredPrompt });
});
}
onClick(e) {
// hide our user interface that shows our A2HS button
// addBtn.style.display = "none";
// Show the prompt
const { deferredPrompt } = this.state;
console.log(
" ~ file: AddToHomeScreenButton.js:49 ~ AddToHomeScreenButton ~ onClick ~ deferredPrompt",
deferredPrompt
);
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then((choiceResult) => {
console.log(
" ~ file: AddToHomeScreenButton.js:53 ~ AddToHomeScreenButton ~ deferredPrompt.userChoice.then ~ choiceResult",
choiceResult
);
console.log(
" ~ file: AddToHomeScreenButton.js:55 ~ AddToHomeScreenButton ~ deferredPrompt.userChoice.then ~ choiceResult.outcome",
choiceResult.outcome
);
if (choiceResult.outcome === "accepted") {
console.log("User accepted the A2HS prompt");
} else {
console.log("User dismissed the A2HS prompt");
}
this.setState({ deferredPrompt: null });
});
}
render() {
const { deferredPrompt } = this.state;
return (
<span>
{!!deferredPrompt && (
<Button
className=".add-button"
color="danger"
type="button"
onClick={this.onClick}
>
Add to home screen
</Button>
)}
</span>
);
}
}
But, nothing happens and I have no idea why. I check the console in the desktop and the code that's inside this:
window.addEventListener("beforeinstallprompt", (e) => {
does not get executed.
I think this makes sense, since I believe this feature isn't supposed to work on desktopp. But, it also doesn't work on mobile in the deployed app.
But, as I said, I managed to add the app to my Android home screen using the chrome Add to home screen button. And it works like a native app.
I found here that there could be several reasons why the beforeinstallprompt is not getting triggered
beforeinstallprompt will only be fired when some conditions are true :
- The PWA must not already be installed Meets a user engagement
- heuristic (previously, the user had to interact with the domain for at least 30 seconds, this is not a requirement anymore).
- Your web app must include a web app manifest.
- Your web app must be served over a secure HTTPS connection.
- Has registered a service worker with a fetch event handler.
All of these conditions are met.
This is the web app manifest:
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
And there is a service worker file:
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (!installingWorker) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' }
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(!!contentType && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
When I open the app on the desktop browser, this is what I see in Application>Manifest:
But, I suppose these aren't relevant to the mobile phone browser. Plus, the app was indeed installed using the chrome add to home screen button. So it is installable.
Any idea how to debug why the button I added doesn't work and how to fix it?