Skip to content Skip to sidebar Skip to footer

Does Service Worker Request, Response From Server Continuously?

I'm using server send event to display a notification.I have created a service worker and i used EventSource to connect with the server (in my case i used a servlet. ) once i run t

Solution 1:

Service workers have a limited lifetime, you shouldn't use things like web sockets or server sent events. Push notifications are implemented in a different way.

In your page, you need to subscribe the user for push notifications. The subscription is an endpoint URL (and a set of keys, if you plan to use payloads). Once the user is subscribed, you need to send the subscription information to your server.

The server will send a push notification to the user via a POST request to the endpoint URL.

The service worker will be awakened when a push notification arrives, its 'push' event handler is going to be executed.

A simple example (for more complex ones, take a look at the ServiceWorker Cookbook).

Page

// Register a Service Worker.
navigator.serviceWorker.register('service-worker.js')
.then(function(registration) {
  // Use the PushManager to get the user's subscription to the push service.return registration.pushManager.getSubscription()
  .then(function(subscription) {
    // If a subscription was found, return it.if (subscription) {
      return subscription;
    }

    // Otherwise, subscribe the user (userVisibleOnly allows to// specify that you don't plan to send notifications that// don't have a visible effect for the user).return registration.pushManager.subscribe({
      userVisibleOnly: true
    });
  });
}).then(function(subscription) {
  // subscription.endpoint is the endpoint URL that you want to// send to the server (e.g. via the Fetch API or via// XMLHTTPRequest).console.log(subscription.endpoint);

  // Here's an example with the Fetch API:fetch('./register', {
    method: 'post',
    headers: {
      'Content-type': 'application/json'
    },
    body: JSON.stringify({
      endpoint: subscription.endpoint,
    }),
  });
});

Service Worker

// Register event listener for the 'push' event.self.addEventListener('push', function(event) {
  // Keep the service worker alive until the notification is created.
  event.waitUntil(
    self.registration.showNotification('Title', {
      body: 'Body',
    })
  );
});

Server

In the server, simply send a POST request to the endpoint URL. For example, with curl:

curl -X POST [endpointURL]

Or, if you're using Node.js, you can use the web-push library (https://github.com/marco-c/web-push):

var webPush = require('web-push');
webPush.sendNotification(req.query.endpoint, req.query.ttl);

In Java, you could use this class (https://github.com/marco-c/java-web-push) that hides the details of the implementation and the differences between the protocols in the current versions of Firefox and Chrome (differences destined to disappear since Chrome is going to use the Web Push protocol soon). Here's a "manual" example with a push service that implements the Web Push protocol (currently only works with Firefox):

URLurl=newURL(endpointURL);
HttpURLConnectionconn= (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");

OutputStreamWriterwriter=newOutputStreamWriter(conn.getOutputStream());

writer.write("");
writer.flush();
String line;
BufferedReaderreader=newBufferedReader(newInputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
  System.out.println(line);
}
writer.close();
reader.close();

Post a Comment for "Does Service Worker Request, Response From Server Continuously?"