-
Notifications
You must be signed in to change notification settings - Fork 320
Description
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:
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:
<!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 (tested in Chrome for Android version 44 and 45).
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.