Avoiding PWA to reload when using Web Share Target API

557 views Asked by At

I'm working on a PWA that plays music. It accepts shared URLs from other android apps via Web Share Target API.

The problem : Whenever something is shared via the API (which uses GET request)I my PWA is reloded (as expected). And the already playing Music stops because of that.

Is there any way that page doesn't reload ?

Currently fetching shared params with this code.

const parsedUrl = new URL(window.location);

My PWA is a Single Page application

Thanks

1

There are 1 answers

0
DenverCoder9 On

One way to prevent reloading is by setting up a fake path in your Web Application Manifest that solely serves for the purpose of receiving shares (note that this uses HTTP POST and "multipart/form-data" encoding [so later you can extend the app to receive entire files]):

{
    "share_target": {
        "action": "/receive-shares",
        "method": "POST",
        "enctype": "multipart/form-data",
        "params": {
            "title": "name",
            "text": "description",
            "url": "link"
        }
    }
}

Then in your service worker's fetch handler, you deal with the incoming shares and redirect the user to the home:

self.addEventListener('fetch', (e) => {
  if ((e.request.url.endsWith('/receive-shares')) &&
      (e.request.method === 'POST')) {
    return e.respondWith((async () => {
      // This function is async.
      const formData = await fetchEvent.request.formData();
      // Do something with the URL…
      const url = formData.get('url');
      // Store the URL, process it, communicate it to the clients…
      // You need to redirect the user somewhere, since the path
      // /receive-shares does not actually exist.
      return Response.redirect('/', 303);
    })())
  }
  /* Your regular fetch handler */
})