cubiq / add-to-homescreen

Add to home screen call-out for mobile devices
http://cubiq.org/add-to-home-screen
2.29k stars 748 forks source link

Recognized 'pinned' behavior in Android Chrome #254

Open ThommyTheThird opened 7 years ago

ThommyTheThird commented 7 years ago

From the docs of ATH v3 you were saying that the window.navigator.standalone property wasn't supported for Chrome and that there was no way of recognizing whether a Chrome user was opening the page from the homescreen or not.

From some Google documentation I managed to find the following:

var launchedFromPinnedHomescreen:Bool = false;
if (window.matchMedia) {
    launchedFromPinnedHomescreen = window.matchMedia('(display-mode: standalone)').matches;
}
//iOS safari doesn't report window.matchMedia correctly, so we rely on navigator.standalone (which Chrome doesn't have)
    if (!launchedFromPinnedHomescreen) {
        if (window.navigator.standalone) launchedFromPinnedHomescreen = window.navigator.standalone;
    }
}

The window.matchMedia functions allows you to look if certain media queries are applied, similar to the media querries used by CSS. iOS Safari also had this function but returns false whenever it was tested, so the window.navigator.standalone property needs to be used there.

I was unsure how to get this information across, so I decided to open an issue for it.

joloco commented 7 years ago

This has apparently been live in Chrome on Android for over a year now, so should be reliable.

I replaced the line which sets ath.isStandalone with:

ath.isStandalone = ('standalone' in window.navigator && window.navigator.standalone) || (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches);

So it checks either the iOS Safari setting, or the Chrome Android setting. If either returns true, then we must be in standalone mode.