简体   繁体   中英

Avoiding PWA to reload when using Web Share Target API

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

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 */
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM