HTML5 mobile app running while phone screen is off?

后端 未结 2 620
迷失自我
迷失自我 2020-12-14 06:08

I\'m interested in creating an HTML5 geolocation-based web app that could still be operating when the phone screen is off (say, tracking how far you\'ve been running when yo

2条回答
  •  醉酒成梦
    2020-12-14 07:05

    You can use Service Workers:

    https://developers.google.com/web/fundamentals/primers/service-workers/

    A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction. Today, they already include features like push notifications and background sync. In the future, service workers might support other things like periodic sync or geofencing.

    To be precise, applications can register a service worker as follows:

    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function() {
        navigator.serviceWorker.register('/sw.js').then(function(registration) {
          // Registration was successful
          console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
          // registration failed :(
          console.log('ServiceWorker registration failed: ', err);
        });
      });
    }
    

    Once the service worker registration is successful, any application logic implemented in sw.js will execute in the background; even if application tab is disabled.

提交回复
热议问题