Skip to content

amp-install-serviceworker: Trigger event when service worker has been update has been installed #18615

Description

@westonruter

At the moment there is no way to alert the user when an updated service worker has been installed. Often pages inform the user of this with a prompt such as:

image

I suggest that amp-install-serviceworker be extended to add support for an updatefound event which can be triggered on the amp-install-serviceworker element.

function install(win, src) {
return win.navigator.serviceWorker.register(src).then(function(registration) {
if (getMode().development) {
user().info(TAG, 'ServiceWorker registration successful with scope: ',
registration.scope);
}
return registration;
}, function(e) {
user().error(TAG, 'ServiceWorker registration failed:', e);
});
}

Perhaps instead of updatefound it would be better to name it updateinstalled since as I understand we're primarily interested in when an updatefound event results in 'installed' === registration.installing.state being true. So perhaps something like so:

function install(win, src) {
  return win.navigator.serviceWorker.register(src).then(function(registration) {
    if (getMode().development) {
      user().info(TAG, 'ServiceWorker registration successful with scope: ',
        registration.scope);
    }

    reg.addEventListener('updatefound', () => {
      reg.installing.addEventListener('statechange', () => {
        if ( 'installed' === registration.installing.state ) {
          const name = 'updateinstalled';
          const event = createCustomEvent(this.win, `${TAG}.${name}`, dict({}));
          Services.actionServiceForDoc(this.element).trigger(this.element, name, event, ActionTrust.HIGH);
        }
      });
    });

    return registration;
  }, function(e) {
    user().error(TAG, 'ServiceWorker registration failed:', e);
  });
}

With something like this in place, an author could then show a notice using amp-bind like so:

<amp-state id="updateAvailable">false</amp-state>
<amp-install-serviceworker 
  on="updateinstalled:AMP.setState({updateAvailable:true})" 
  src="https://www.example.com/serviceworker.js"
  data-iframe-src="https://www.example.com/install-serviceworker.html"
  layout="nodisplay"
></amp-install-serviceworker>
<button hidden [hidden]="! updateAvailable" on="tap:AMP.navigateTo(url=AMPDOC_URL)">
   Update available!
</button>

(Maybe there should be an AMP.reload() action available as well.)

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions