PWA wont open in standalone mode on android

2019-01-24 17:53发布

问题:

I am trying to implement Add To Home Screen on the latest Chrome & Android (7). I have specified "standalone" in the manifest file but the app only opens in the browser. I've gotten the desired behavior before on the same device, but can't seem to reproduce it.

I see that someone had a similar issue in this question. I followed the suggested solution - validating PWA properties with Lighthouse - but even with a perfect 100 Lighthouse score, I am still unable to get the app to open in standalone mode.

Any ideas?

My code for reference (which is also on GitHub & hosted on GitHub Pages):

Index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>A2HS Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#0077c2"/>
    <link rel="manifest" href="manifest.json">
  </head>
  <body>
    <p>Add To Home Screen</p>
    <script>
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('sw.js')
        .then(reg => console.log('Registration success. Scope is ', reg.scope))
        .catch(err => console.log('Registration failed. ', err));
      }
    </script>
  </body>
</html>

sw.js

const cacheName = 'a2hs-test';
const resourcesToCache = [
  'index.html',
  'manifest.json',
  'icons/icon-512.png',
  'icons/icon-256.png',
  'icons/icon-96.png',
];

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return cache.addAll(resourcesToCache);
    })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    })
  );
});

manifest.json

{
  "short_name": "A2HS",
  "name": "Add To Home Screen",
  "theme_color": "#0077c2",
  "background_color": "#42a5f5",
  "start_url": "index.html",
  "display": "standalone",
  "icons": [
    {
      "src": "icons/icon-96.png",
      "sizes": "96x96"
    },
    {
      "src": "icons/icon-256.png",
      "sizes": "256x256"
    },
    {
      "src": "icons/icon-512.png",
      "sizes": "512x512"
    }
  ]
}

EDIT:

I ran into a similar issue again on v63 & Canary v66, and it seems like using localhost caused the same issue - unable to launch in standalone. Hosting the exact same code and accessing the HTTPS site allowed me to launch in standalone.

回答1:

As per the comments, this appears to simply be a bug that was fixed in Chrome 63+.

EDIT:

See edits above - hosting via HTTPS also solved the same issue for me on v63 and Canary v66. Localhost might not be sufficient to allow apps to launch in standalone mode.



回答2:

One solution I found is to use the proxy from developer tools under remote devices. You have to use USB cable to connect your device and proxy the application, this way you can use localhost as well.