Skip to content

Service worker, postMessage to the client, ClassCastException, ServiceWorkerClient #180

@vals-productions

Description

@vals-productions

I was trying to post a message to the WindowClient from service worker.

The code is a GWT generated JavaScript accessed from service-worker.js (plain JavaScript) through JsInterop.

Main thread JavaScript module posts the message to the service worker, service worker processes the message and sends the message back to the calling client.

Below is the code that demonstrates approaches attempted.

...
private void postMessage(String payload, String clientId) {
  ServiceWorkerGlobalScope swgs = (ServiceWorkerGlobalScope) DomGlobal.self;
  ServiceWorkerClients clients = swgs.getClients();

  // approach 1
  // the exception is ClassCastException thrown in get(...) and the client is not received into then
  clients.get(clientId).then(client -> {
	if (client != null) {
		client.postMessage(payload);
	}
	return null;
  });

  // approach 2
  clients.matchAll().then(all -> {
    for (int i = 0; i < all.length; i++) {
       Object windowClient = all.at(i); // windowClient is actually an instance of WindowClient as seen in the debugger
       if (windowClient instanceof ServiceWorkerClient) {
         // it never gets here
       }
       // force cast gives ClassCastException
       ServiceWorkerClient swc = Js.cast(windowClient); 
       swc.postMessage(payload);
    }
     return null;
  });
...

As mentioned in the code snippet above, what is actually received in the approach 2 is WindowClient .

I was able to workaround the issue by passing an array of windowClients ( all in the snippet above) through JsInterop and posting the message from JavaScript and it worked.

@JsType(isNative = true)
public class UtilsJs {
   public static native void postMessage(Object windowClients, String clientId, String payload);
}

The browser was Chrome.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions