[ServiceWorker] When does the openWindow promise resolve? (#728)

I am trying to send a message to a page from a serviceWorker. The goal is to let the page respond to the click (opening what the notification is about).

With this code inside a `notificationclick` event handler:

```javascript
clients.openWindow(url).then(function(client) {
    client.postMessage(message);
});
```

There is a race between delivering the message event and attaching the `message` event listener (while loading the page). Experimentally, I have found that the only way to receive the event is to add the `message` event listener before `<html>`, like so:

```html
<!DOCTYPE html>

<script>
navigator.serviceWorker.addEventListener('message', function (event) {
    console.log('got message:', event.data);
});
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    (...)
```

This appears very unreliable to me.

A possible solution is letting the promise resolve around the `DOMContentLoaded` or `load` events. Another option could be to let the service worker detect when the page is loaded (via an event).

I have used a workaround: sending the needed information in the URL fragment identifier and navigating to the proper URL using `history.replaceState` in the client (webpage). This works reliable so far.

---
Reply to this email directly or view it on GitHub:
https://github.com/slightlyoff/ServiceWorker/issues/728

Received on Thursday, 30 July 2015 18:33:27 UTC